Core_Java_New[1]
Core_Java_New[1]
Introduction To Java
Java was developed at Sun Microsystem. The history of Java can be traced
back to a project called Green project in SUN. Patric Naughton, Bill Joy, James
Gosling, Mike Sheridan were some of the people working on the Green project.
The aim of this project was to develop software for smart consumer electronic
devices such a complex remote controls. At first developer tried using C++ to
develop the software but they faced a number of problems.
In 1994, the Internet and the World Wide Web became popluar. The people at
Sun realized that Java was suitable to develop applications for the Internet.
During that time Mosaic the First Graphical Browser was released, with
this people on different types of machines and operating systems started accessing
the applications available on the web.
r, which they later renamed as Hot Java. Sun Formally released Java and hot
Java in 1995. Hot Java proved to the world that it was possible to develop complex
applications by using java.
Members of the Oak team realized that java would provide the required
cross-platform independence from the hardware network, and the operating
system. Very soon, Java became an integral part on the web.
1
1.3 Comparison of Java with C:
Although Java adds some new things, it is most distinctive for what is left out.
▪ Templates
▪ Operator overloading
▪ Multiply inheritance
▪ Multiple APIs in java
2
Java is....
Java was designed to be easy for the professional programmer to learn and
use effectively Java makes itself by not having surprising features.
Since it exposes the inner working of a machine, the programmer can perform
his desired actions without fear. Unlike other programming systems that provide
dozens of complicated ways to perform a simple task,
Anyone can master Java with a little bit of programming experience. If the
user already understands the basic concepts of object-oriented programming,
learning Java will be much easier.
Secure
Today everyone is worried about safety and security. People feel that
conducting commerce over the Internet is as safe as printing their credit card
number on the first page of a newspaper. Threatening of viruses and system hackers
also exists. To overcome all these fears Java has safety and security as its key
design principle.
Portable
In Java, the same mechanism that gives security also helps in portability.
Many types of computers and operating systems are in use throughout the world and
are connected to the Internet. For downloading programs through different platforms
connected to the Internet, some portable, executable code is needed.
Java's answer to these problems is its well-designed architecture.
Object-oriented
Java was not designed to be source-code compatible with any other language.
Java team gave a clean, usable, realistic approach to objects. The object model in
Java is simple and easy to extend, while simple types, such as integers, are kept as
high-performance non-objects.
3
Robust
▪ Memory management
▪ 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.
Multithread
The Java run-time system enables the user to construct smoothly running
interactive systems.
Architecture-Neutral
The Java designers worked hard in attaining their goal "write once: run
anywhere, anytime, forever" and as a result the Java Virtual Machine was
Developed.
This code can be interpreted on any system that has a Java Virtual Machine.
Most of the earlier cross-platform solutions are run at the expense of performance.
Other interpreted systems, such as BASIC, Tel and PERL, suffer from almost insoluble
performance deficits.
Java byte code was carefully designed so that it can be easily translated into
active machine code for very high performance by using a just-in-time compiler.
4
Distributed
Dynamic
Java program carry with them extensive amounts of run-time information that
is used to verify and resolve accesses to objects at run time. Using this concept it is
possible to dynamically link code. Dynamic property of java adds strength to the
applet environment, in which small fragments of byte code may dynamically updated
on a running system.
The bytecodes are then interpreted by the Java Interpreter. The java
interpreter is called the Java Virtual Machine (JVM) or the Java Runtime Engine. The
JVM convers the bytecodes into the machine code that be understood by the specific
computer on which it is run.
M/C code
Java Program
Interpreter 01001 Computer
Running bytecode on a JVM is the reason that Java software is "Write Once Run
Anywhere". Java executables provide a single binary that runs on every processor.
For example, the same Java program can run on Windows NT. Solaris, or
Macintosh.
5
Java
Program
Compiler
The Java API supports all kinds of programs with packages of software
components that provide a wide range of functionality.
The Essentials: Objects, Strings, Threads, Numbers, Input and Output, Data
structures, System properties, Data and Time, and so on.
Internationalization: Help for the writing programs that can be localized for users
worldwide. Program can automatically adapt to specific locales and be displayed in
the appropriate language.
Software component: Known as Java Beans, can plug into existing component
architectures such as Microsoft's OLE/COM/Active-X architecture, OpenDoc, and
Netscape's Liver Connect.
Java not only has a core API, but also standard extensions. The standard
extensions define APIs for 3D, Servers, Collaboration. Telephone, Speech,
Animation, and more.
6
Packages of the Java API
JDK is a collection of tools that are necessary to work with java Applet and
applications.
▪ javac - the compliser, checks for syntactical error and converts syntax free
java program into bytecode.
▪ java - the Interpreter, executes the bytecode
▪ appletviewer - used to test applets on machines which does not havejava
enabled web browser
1.10.1 Applications:
JAVA applications can read from and write to files on the local computers. Standalone
applications make use of the resources of just a single computer. It is stored on the
hard disk of the local computers.
1.10.2 Applets:
Applets are JAVA programs that are used to develop web pages.
Java applet are programs that require a Web Browser with a JVM to run.
7
Summary
Advantages of JAVA:
1. It is easy to learn.
2. Everything in JAVA is in the form of Classes and Objects.
3. It provides the features of Abstraction, Encapsulation, Polymorphism
and Inheritance.
4. JAVA programs can access data across a network.
5. The byte code can be executed on a variety of computers running on
different operating system(Platform independent).
6. Java does not allow a programmers to manipulate the memory of the system.
7. Java programs are faster when compared to programs written in other
interpreter-based languages.
8. It allows multiple parts of a program to run simultaneously.
9. There are two types of JAVA programs 1.Application 2.Applets
8
2. Java Programming and Fundamentals
Program:
class Example
{
//program begins with a call to the main method
2.2 Comments:
They are:
(i) A Single Comment statement précised by all the text which follows the
//, which treated as a comment and ignored by the compiler.
(ii) A Multiline Comment enclosed within the two character sequence /*…*/
(iii) The third type called the Documentation Comment begins with a /**
and ends with a */. They are used to produce a HTML file that documents
the program.
Every program in Java is a class. So, the first line of any Java program is
always class followed by the name of the program. The name of the program can be
anything it should only begin with an alphabet and contain no spaces.
9
The next line contains four words public, static, void and main.
public: The method main can be accessed by any other class.
static: The method main is associated with the class where it is declared.
void : The method main does not return any value.
main: main is the name of the method which can execute at first.
The method name main is followed by (String args[]). This means that the
method main accepts an array of string from the command line.
javac <filename>.java
Eg: Example.class
6. To run a java program, executes the interpreter specifying the name of the
class file on the command line.
10
2.3.2 Data Types
A variable's data type determines the values that the variable can contain and
the operations that can be performed on it.
For example: Integers can contain only integral values (both positive and negative).
You can perform operations, such as addition, on integer variables.
The java programming language has two major categories of data types:
▪ Reference (object)
For example: the value of an int is an integer, the value of a char is a 16-bit
Unicode character, and so on.
A reference type variable is not the array or object, but rather a way to reach
it.
(Integers)
8-bit two's complement (1 byte)
byte Byte-length integer
(Real numbers)
Single-Precision
float 32-bit (4 byte)
floating point
Double-precision
double 64-bit (8 byte)
floating point
(Other types)
11
In other languages, the format and size of primitive data types may depend
on the platform on which the program is running. In contrast, the java language
specifies the size and format of its primitive data types. Hence, you don't have to
worry about system dependencies.
Syntax
datatype <identifiername>;
In addition to the name and type that you explicitly given to a variable, a
variable also has scope.
Scope : is the life span of the variable it determines what sections of code
can use the variable. The location of the variable declaration, that is where the
declaration appears in relation to other code elements, determines its scope.
12
//real Numbers
if(Character.isUpperCase(aChar))
{
System.out.println("The Character "+aChar +" is upper
case.");
}
else
{
System.out.println("The Character "+aChar +" is lower
case.");
}
System.out.println("The value of aBoolean is "+aBoolean);
}
}
By Convention:
Variable names begin with a lowercase letter and Class names begin
with an uppercase letter. If a variable name consists have more than one word,
such as isVisible, the word are joined together and each word after the first begins
with an uppercase letter. Constant in java are defined as Fully uppercase
eg: Math.PI
13
3. Operators in Java
An operator is a symbol that specifies an operation to be performed.
1. Arithmetic Operator
2. Relational Operator
3. Conditional Operator
4. Logical Operator
5. Assignment Operator
6. Increment/Decrement Operator
7. Comma Operator
8. Bitwise Operator etc.,
Java has five basic arithmetic operators. Each of these operators takes two
operands, one on either side of the operator.
14
Command Line Arguments (Keyboard Input) :
class Argument
{
public static void main(String args[])
{
int a,b,c;
float f;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=Integer.parseInt(args[1]);
f=(float)((a+b)/c);//type cast to float
System.out.println(“Result =”+f);
}
}
To run this above program after complied
C:\>java Argument 5 2 2
OUTPUT : 3.5
a=Float.parseFloat(args[0]);
b=Float.parseFloat(args[1]);
import java.util.*;
class Scan
{
public static void main(String arg[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int i = sc.nextInt();
System.out.println("Enter a number");
int j=sc.nextInt();
int k=i+j;
System.out.println(k);
}
}
15
3.2 Relational Operators
There are several expression for testing equality and magnitude. All these
expressions return a Boolean value.
A B A&&B A||B A ^B
True True True True False
True False False True True
False True False True True
False False False False False
NOT(!) True -> False False-> True
Syntax:
where <test> is the condition to be tested. If the condition returns true than
statement give in <pass> will be executed. Otherwise, the statement gives in<fail>
will be executed.
Example: c=a>b?a:b
Check for simple expression with true or false
The assignment operators used in c and C++ are also used in java. A selectin
of assignment operators is given
Syntax:
1. Variable = Constant eg: a=10;
2. Variable1 = Variable2 eg: a=b;
3. Variable = Expression eg: a=a+b;
16
3.5 Increment and Decrement Operators
Example:
a=10;
b=a++;
Result is : a=11
b=10
Example:
a=10;
b=++a;
Result is : a=11
b=11
Example:
a=10;
b=a--;
Result is : a=9
b=10
Example:
a=10;
b=++a;
Result is : a=9
b=9
17
3.6 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 int table:
Operators Meaning
& Bitwise AND
| Bitwise Or
^ Bitwise XOR
<< LeftShift
>> RightShift
~ Bitwise complement
X&=Y AND assignment
X|=Y OR assignment
X^=Y XOR Assignment
Program :
class Bitwise
{
public static void main(String arg[])
{
int x=5;
int y=3;
System.out.println(x&y);
System.out.println(x|y);
System.out.println(x^y);
System.out.println(x>>2);
System.out.println(x<<2);
}
}
OUTPUT :
1
7
6
1
20
18
4. Control Statements
This Statement will alter the program sequence and it is used to make a decision
1. Simple if Statement
2. if…else
3. Nested if…else
4. else…if ladder or or Mutliple else if
5. (if…elseif..else)
6. Switch..case statement.
7. Loops
Syntax:
if (condition)
{
statement(s);
}
normal statement;
Explanation:
When the condition is true the statement(s) are executed and then control
is passed to the statement immediately after the if statement. If the condition is
false, control is passed directly to the statement following the if statement, ie.,
Normal statement will execute.
Program:
class IfDemo
{
public static void main(String arg[] )
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
if(a>b)
{
big=a;
}
if(b>a)
{
big=b;
}
System.out.println(“Big= "+big);
19
OUTPUT :
10
20
Big=20
Syntax:
if(condition)
{
true block statement(s)
}
else
{
false block statement(s);
}
statement-x;
Explanation:
Here, If the condition is true, the true block statement(s) are executed and
if the condition is false, the false block statement(s) are executed. Statement -x
will execute always after the if ..else block
Program:
class IfElseDemo
{
public static void main(String arg[] )
{
int a =100 ,b=20,big=0;
if(a>b)
{
big=a;
}
else
{
big=b;
}
System.out.println(“Big= "+big);
OUTPUT :
100
20
Big=100
20
4.3 Nested if statements
Sometimes, while writing programs, it becomes necessary to check a second
condition based on the result of the first. In such cases, the second if statement has
to be nested within the first if statement. Such statement are called Nested if
statement
Syntax:
if(condition1)
{
.............
.............
if(condition2)
{
............
............
}
else
{
..........
...........
}
}
else
{
..........
..........
}
Program:
class NestedIfDemo
{
public static void main(String arg[] )
{
int a =67 ,b=89,c=45,big=0;
if(a>b)
{
if(a>c)
big=a;
else
big=c;
}
else
{
if(b>c)
big=b;
else
big=c;
21
}
System.out.println(“Big= "+big);
}
}
OUTPUT :
67
89
45
Big=89
Syntax:
if(condition1)
{
statement1
}
else if(condition2)
{
statement2
}
else if(condition3)
{
statement3
}
----------------------
----------------------
else
{
default statement
}
statement-x;
22
class NestedIfDemo
{
public static void main(String arg[])
{
int m1=56,m2=45,m3=59,m4=50,m5=91;
double per=(double)0.0;
int tot= m1+m2+m3+m4+m5;
per=tot/5.0;
System.out.println("Total Marks = "+tot);
System.out.println("Percentage = "+per);
if(per>=75)
{
System.out.println("Distinction");
}
else if(per>=60)
{
System.out.println("First Class");
}
else if(per>=50)
{
System.out.println("Second Class");
}
else if(per>=40)
{
System.out.println("Third Class");
}
else
{
System.out.println("No Grade");
}
}
}
OUTPUT
Total Marks = 301
Percentage = 60.2
First Class
Syntax:
switch(expression)
{
case constant1:
statement1
break;
case constant2:
statement2
23
break;
-------------
-------------
case constant n:
statement n
break;
default:
default statement
break;
}
class SwitchDemo
{
public static void main(String arg[])
{
int n = Integer.parseInt(arg[0]);
switch(n)
{
case 1:
System.out.println("The number is one");
break;
case 2:
System.out.println ("The number is two");
break;
case 3:
System.out.println ("The number is three");
break;
default:
System.out.println ("The number is not
between 1 and 3");
break;
}
System.out.println ("\nEnd of program");
}
}
OUTPUT
C:\> java SwitchDemo 2
24
4.6 Loops in Java
Computers are best suited for applications where a sequence of steps has to be
repeated several times. The program construct that is used to repeat such a
sequence of steps is called as loop. Every loop consists of condition that determines
the number of times those statements are to be repeated. There are three different
loop statements in Java, they are
1. while Loop
2. do-while Loop
3. for Loop
The while loop executes a set of code repeatedly until the condition returns false.
Syntax :
while(condition)
{
statement(s);
}
This loop is executed as long as the condition is true. When the condition
becomes false control is passed to the statement following the while statement.
Program:
class WhileDemo
{
public static void main(String arg[])
{
int n=Integer.parseInt(arg[0]);
int i=1,s=0;
while(i<=n)
{
s=s+i;
i++;
}
System.out.printlnf("Sum of n Number is “+s);
}
}
OUTPUT :
10
55
25
do
{
statement(s);
}while(condition);
Program:
class DoWhileDemo
{
public static void main(String arg[])
{
int n=Integer.parseInt(arg[0]);
int i=1,f=0;
do
{
f=f*i;
i++;
} while(i<=n);
System.out.printlnf("Product of a given Number is “+s);
}
}
OUTPUT :
10
55
Syntax :
Initialization
Statement that assigns an initial value to the control variable. The control
variable is a variable that is used to keep track of the number of times the loop has
to be repeated. This statement is executed once at the beginning of the loop.
Condition
A condition that compares the control variable with a value to find out if the
loop has been repeated the required number of times. If the condition is true, the
loop is repeated again, If the condition is false, control is passed to statement after
the for loop. The test is performed at the start of every iteration.
26
Increment
A statement that increases (or decreases) the value of the control variable by
a specified number every time the loop is executed. This statement in executed at
the end of every iteration.
Program:
class ForDemo
{
public static void main(String arg[])
{
int n=Integer.parseInt(arg[0]);
int s=0;
if(n==0)
System.out.println(s);
else
for(int i= 1;i<=n;i++)
{
s=s+i;
}
System.out.printlnf("Sum of n Number is “+s);
}
}
OUTPUT :
10
55
The break keyword halts the execution of the current loop and forces control
out to the loop. The term break refers to the act of breaking out of a block of code.
Inorder to refer to a block by name, java has a label construct that assigns a name to
every block.
for(int i=2;i<n;i++)
{
if(n%i==0)
break;
else
continue;
}
27
if(i==n)
System.out.println("Given number is prime");
else
System.out.println ("Given number is not prime");
}
OUTPUT:
5
Given number is prime
Program 2:
class BreakDemo2
{
public static void main(String arg[])
{
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");
}
}
}
OUTPUT :
Before the break
This is after b
Program:
class ContinueDemo
{
public static void main(String arg[])
{
for(int i=0; i<10; i++)
{
System.out.print(i+" ");
if(i % 2 == 0)
{
continue;
}
System.out.println();
28
}
}
}
OUTPUT:
0 1
2 3
4 5
6 7
8 9
When one loop statement is embedded within the another loop, it is called as
a Nested Loop. In java, multiple for loops(and while loops are do-while loops) can
be nested within each other.
Program:
class Nest
{
public static void main(String arg[])
{
int n;
n=Integer.parseInt(arg[0]);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(j+" ");
}
System.out.println();
}
}
}
OUTPUT:
Java Nest 5
1
1 2
1 2 3
1 2 3 4
1 2 3 3 4 5
29
5. Arrays in Java :
An array is an object that stores a list of items continuesly of same data type. An
array is used to store data continuelsy in the memory of the computer.
or
int a[];
-------------------;
-------------------;
a[]= new int[5];
import java.io.*;
class SingleArray
{
public static void main(String arg[])
{
DataInputStream in = new DataInputStream(System.in));
System.out.println("Enter array size ");
String str=in.readLine();
int size=Integer.parseInt(str);
30
5.2 Two Dimension Array:
Program:
import java.io.*;
class Array
{
public static void main (String arg []) throws IOException
{
DataInputStream kb= new DataInputStream(System.in);
31
6. Methods (Functions)
Functions are an integral and important part of Object programming
language. In object oriented programming languages, functions are called as
Methods
You have already come across several such methods in earlier chapters. Some
examples are System.out.println(), readLine(), Integer.parseInt();
Syntax:
methodName(parameter list);
Type 1:
class Method1
{
public static int sum(int a, int b)
{
int c;
c=a+b;
return(c);
}
32
public static void main(String args[])
{
int k;
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
k=sum(x,y);
System.out.println(k);
int z=sum(k,x);
System.out.println(z);
}
}
Type 2:
class Method2
{
public static int biggest()
{
int a=10,b=20;
if(a>b)
return(a);
else
return(b);
}
public static void main(String args[])
{
int big;
big=biggest();
System.out.println("Biggest of two nos = "+big)
}
}
Type 3:
class Method3
{
static void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
System.out.println("X = "+ x +"Y = "+ y);
}
public static void main(String args[])
{
int a=10, b=20;
swap(a,b) //calling of swap function
System.out.println("End of main function");
}
}
33
Type 4:
class Method4
{
static void swap()
{
int a=10, b=10,t;
t=a;
a=b;
b=t;
System.out.println("A = "+ a +"B = "+ b);
}
public static void main(String args[])
{
swap() //calling of swap function
System.out.println("End of main function");
}
}
34
7. Object Oriented Programming (OOPs)
Object Oriented Programming paradigm is playing an increasingly significant
role in the design and implementation of software development. It simplifies the
development of large and complex software systems and helps in the production of
software’s,
Which is Modular, Easily understandable, Reusable, and Adaptable to
changes.
The object oriented approach centers around modeling the real world
problems in terms of objects.
Abstraction: is a feature that makes only the necessary details available to the
user.
Eg: Consider a TV. When you watch TV, you are not bothered about the inner details
of the parts. You ignore the various complex individual parts that forms the TV.
7.1.1 Encapsulation: is a mechanism that binds together code and the data where
code manipulates the data, and keep both safe from outside interference and
misuse.
Encapsualtion is a protective wall that prevents the code and data from beging
randomly accessed by other code defined outside the wall.
The concept of hiding the non-essential details from the user is called Encapsulation.
Eg: Consider an automobile. The information about the engine is hidden from the
user.
7.1.3 Polymorphism: is a feature that allows one Interface to be used for a general
class of action. More generally, the concept of polymorphism is often expressed
by the phrase "one interface, multiple methods". This means one common
name for a method with different parameters.
▪ Method Overloading
▪ Method Overridding
7.2 Class
A class is a prototype that defines the Data and Code common to all objects
of a particular kind.
A class defines the structure and behaviour of the objects. The elements of a
class are called members. Code and data are two important elements of a class.
35
The code that acts on the data is called method. The data defined by the calss is
called variables.
Data Data
Data1 int a
Data2 int b
Data3 int c
Methods Methods
Method1() sum()
Method2() sub()
Method3() mul()
Syntax:
Syntax:
36
7.3 Objects as Instance:
The new operator creates a single instance of a named class and returns a
reference to that object.
Syntax:
class-name Objectname=new class-name( );
This statement combines the two steps just described. It can be rewritten like
this to show each step clearly.
Statement Effect
Box null
mybox; mybox
Width
mybox = new Box();
Height
mybox
Depth
Box object
Declaring an object of type
box
7.3.2 Dot Operator (is use to access instance variables and methods):
The dot notation is used to obtain the value of the instance variable. It has
two parts namely, the object on the left side of the dot and the variable on the right
side of the dot. Dot expression are evaluated from left to right.
Syntax:
<object Reference> . <variable name>
<objectReference> . <method name>
37
Program: Example for class using Instance variables only.
class Box
{
double width;
double height;
double depth; //instance variables
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox =new Box( ); //instance of class
double vol; //local variable
}
}
OUTPUT: 45
Object reference variables act differently than you might expect when an
assignment takes places. For example, what do you think the following fragment
does?
For Example:
Here, b1 has been set to null, but b2 still points to the original object.
Note: when you assign one object reference variable to another object reference
variable you are not creating a copy of the object, you are only making a copy
of reference
38
7.4 Methods:
7.4.1 Introduction to Methods
Class usually consists of two things: Instance variable and Methods. The
topic of methods is a large one because java gives them so much power and
flexibility.
Syntax:
<access specifier><return-type>method-name(argument list)
{
local declaration;
function body;
return statement;
}
7.5.1 public:
The members, which are declared as a public, can be accessed by any method
in the outside of the class.
class Item
{
public int a,b,c;
class MethodDemo
{
public static void main(String args[])
{
Item t=new Item();
int k; //local variable
t.a=10;
t.b=20;
t.c=t.a+t.b;
System.out.println(t.c);
}
}
39
Program: Example for Public Methods and Public instance variables in a class:
class PublicVar
{
public int a,b,c;
public int sum(int x, int y)
{
int z;
z=x+y;
return(z);
}
}
class MethodVariable
{
public static void main(String args[])
{
PublicVar p=new PublicVar( );
p.a=20;
p.b=10;
p.c=p.sum(p.a,p.b);
System.out.println(p.c);
}
}
7.5.2 Private:
A Member Data or Methods can only be accessed by the methods of the same
class. The private instance variable is not accessible from the outside of the class.
Program :
class PrivateVar
{
private int a,b,c;
}
class PrivateDemo
{
public static void main(String args[])
{
PrivateVar p=new PrivateVar();
p.a=20;
p.b=10;
p.c=p.a+p.b;
System.out.println(p.c);
}
}
In this program, it gives Six Errors as the variables are declared as private in
the class PrivateVar and it cannot be accessed by the PrivateDemo class.
40
Program :
class Item
{
private int a,b,c;
public void sum( )
{
a=20;b=10;
c=a+b;
System.out.println ( c );
}
}
class PrivateAccess
{
public static void main(String args[])
{
Item t=new Item( );
t.sum( );
}
}
class Item
{
private int sum(int a, int b)
{
int c;
c=a+b;
return ( c );
}
public void arith(int x, int y)
{
int z;
z=sum(x,y);
System.out.println(z);
}
}
class PrivateAccess1
{
public static void main (String args[])
{
Item t=new Item( );
t.arith(20,10);
}
}
7.4.3 Protected
This specifier is a relationship between a class and its present and future
subclasses. The subclasses are closer to the parent class than any other class. This
level gives more protection and narrows visibility.
The protected access specifiers have been deal with Inheritance and packages
in java.
41
7.5 Static Keyword
The static modifier can be applied to variables, methods and even to a strange
kind of code that is not a part of a method. Static features are associated with a
class rather than being associated with an individual instance of a class
Program :
class item
{
public static int a;//class variable
}
class staticVar
{
public static void main(String args[])
{
item t= new item();
item t1= new item();
t.a=10;
t1.a=20;
System.out.println(t.a);
System.out.println(t1.a);
}
}
Class methods, like class variables, are available to instance of the class and
can be made available to other classes. Class method can be used anywhere
regardless of whether an instance of the class exist or not. Class method is defined
as given below
Syntax:
42
Methods declared as static have several restrictions:
class UseStatic
{
static int a=3;
static int b;
static void meth(int x)
{
System.out.println (“ X = “ + x);
System.out.println (“ a = “ + a);
System.out.println (“ b = “ + b);
}
static //static block
{
System.out.println (“Static block initialized”);
b=a*4;
}
OUTPUT:
Static block initialised
X = 42
a=3
b = 12
As soon as the UseStatic class is loaded, all of the static statements are run.
First a is set to 3 , then the static block executes(printing a message), and finally, b
is initialized to a*4 or 12. the main() is called, which calls meth(), passing 42 to x.
The static keyword indicates that it is a class method and can be accessed
without creating an object. The class methods, unlike instance methods, are not
allowed to use instance variables, as these method do not operate on an object.
43
7.7 Method Overloading:
In a class more than one method can have same method name with different
arguments. All the methods distinct in three ways.
Program:
class A
{
public int sum(int a,int b)
{
return(a+b);
}
public int sum(int a,int b,int c)
{
return(a+b+c);
}
public double sum(int a, double b)
{
return(a+b);
}
public double sum(double a, int b)
{
return(a+b);
}
}
class MethodOverDemo
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.sum(20.4,30));
System.out.println(obj.sum(10,20));
System.out.println(obj.sum(10,20,30));
}
}
44
7.8 Constructor:
When the keyword new is used to create an instance of class, java allocates
memory for the object, initializes the instance variable and calls the constructor
methods.
Every class in java by default has a default constructor that does not take
any argument and the body of it does not have any statements.
Program:
class Const
{
public Const()//default constructor
{
int a,b,c;
a=10;
b=20;
c=a+b;
System.out.println( c );
}
}
class ConstDemo
{
public static void main(String args[])
{
Const p=new Const();
}
}
class ConstPara
{
ConstPara(int a,int b)//parameterised constructor
{
int c;
c=a+b;
System.out.println( c );
}
}
class ConstParaDemo
{
45
public static void main(String args[])
{
ConstPara p=new ConstPara(30,10);
}
}
Constructors can also take varying numbers and types of parameters. This
enables creation of objects with the properties required.
Program :
Box()
{
width = -1;
height = -1;
depth = -1;
}
Box(double len)
{
width = height = depth = len;
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
46
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
So far we have only been using simple data types as parameters to methods.
However, it is both correct and common to pass object to methods. For example,
consider the following simple program
Program :
Test(int i, int j)
{
a = i;
b = j;
}
boolean equals(Test o)
{
System.out.println("o.a = "+ o.a + "a = " + a);
System.out.println("o.b = "+ o.b + "b = " + b);
class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, 22);
47
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
A method can return any type of data, including class types that you create.
For example, in the following program, the incrByTen() method returns an object in
which the value of a is ten greater than it is in the invoking object.
Program :
// Returning an object.
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10);
return temp;
}
}
class RetOb
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "
+ ob2.a);
}
}
48
8. Inheritance
It is a process of creating new class from an existing class. The existing class
is called as “Base class (or) super class”. The newly created class is called as
“subclass or derived class”.
Type of Inheritance:-
1) Single Inheritance.
2) MultiLevel Inheritance
3) Hierarchical Inheritance
4) Multiple Inheritance ( for Interface only)
Program:
class A
{
int x,y;
public int sum(int a,int b)
{
x=a;
y=b;
return(x+y);
}
}
class B extends A
{
public int mul(int a, int b)
{
x=a;
y=b;
return(x*y);
}
}
class Single
{
public static void main(String args[])
{
B obj=new B();
System.out.println(obj.sum(20,10));
System.out.println(obj.mul(20,10));
}
}
using object of derived (sub(class)) we can access all the properties of super class.
49
8.2 Multilevel Inheritance :
Program :
class A
{
public int sum(int a, int b)
{
return(a+b);
}
}
class B extends A
{
public int diff(int a, int b)
{
return(a-b);
}
}
class C extends B
{
public int mul(int a,int b)
{
return(a*b);
}
}
class D extends C
{
public int div(int a, int b)
{
return(a/b);
}
}
class Multilevel
{
public static void main(String args[])
{
D d= new D();
System.out.println(d.div(20,10));
System.out.println(d.sum(20,10));
System.out.println(d.diff(20,10));
System.out.println(d.mul(20,10));
}
}
class A
{
A()
{
System.out.println("A is called ");
}
}
class B extends A
{
B()
{
System.out.println("B is called ");
}
50
}
class C extends B
{
C()
{
System.out.println("C is called ");
}
}
class CallCons
{
public static void main(String arg[])
{
C c = new C();
}
}
OUTPUT:
A is called
B is called
C is called
8.4 Super Keyword: Super keyword are used to access data and code of a
super class.
Sytax: super.variable
super.method();
class main
{
int i=12;
}
class sub extends main
{
int i=17;
void display()
{
System.out.println("I = "+i);
System.out.println("Super.i = "+super.i);
}
}
class Super
{
public static void main(String arg[])
{
sub s = new sub()
s.display();
}
}
51
Example 2:
class Super
{
int i;
}
class sub extends Super
{
int i;
sub(int x, int y)
{
i=x;
super.i=y;
}
void display()
{
System.out.println("I in subclass = "+i);
System.out.println("I in superclass = "+super.i);
}
}
class CallSuper
{
public static void main(String arg[])
{
sub s = new sub(10,20);
s.display();
}
}
}
void display()
{
System.out.println("I = "+i+"\nJ = "+j);
System.out.println("K = "+k);
}
}
class CallSuper
{
public static void main(String arg[])
{
52
sub s = new sub(10,20,30);
s.display();
}
}
It is a process of creating a sub class from more than one super class. Java
does not support for multiple inheritance for class
class A
{
Public int arith(int a,int b)
{
return(a+b);
}
}
class B extends A
{
public int arith(int a,int b)
{
return(a-b);
}
}
class c extends B
{
public int arith(int a, int b)
{
return(a*b);
}
}
class D extends C
{
public int arith(int a,int b)
{
return(a/b);
}
}
class Overriding
{
public static void main(String args[])
{
A p1; //(#To create Object reference)
p1=new B();
System.out.println(p1.arith(20,10));
p1=new C();
System.out.println(p1.arith(20,10));
p1=new D();
53
System.out.println(p1.arith(20,10));
p1=new A();
System.out.println(p1.arith(20,10));
}
}
OUTPUT : 10 200 2 30
There are situations in which we will want to define a super class that declares
the structure of a given abstraction without providing a complete implementation of
every altered.
abstract class A
{
abstract public int arith(int a, int b);
class B extends A
{
public int arith (int a, int b)
{
return(a-b);
}
}
class C extends B
{
public int arith(int a,int b)
{
return(a*b);
}
}
class D extends C
{
public int arith(int a,int b)
{
return(a/b);
}
}
class AbstractDemo
{
public static void main(String args[])
{
A p;
54
p=new B();
System.out.println(p.arith(10,20));
p=new C();
System.out.println(p.arith(10,20));
p=new D();
System.out.println(p.arith(10,2));
}
}
OUTPUT:
10
200
2
class FinalVar
{
public static void main(String args[])
{
final int a=10;
a=a+5;//error
System.out.println(a);
}
}
The above program will give a error message.
Final method is used to put a lock on the method to prevent any inheriting
class from changing its meaning. This is done for design reasons when you want to
make sure that a method’s behavior is retained during inheritance and cannot be
overwritten.
class A
{
public int arith(int a,int b)
{
return(a+b);
}
}
class B extends A
{
final public int arith(int a, int b)
{
return(a-b);
}
}
class C extends B
{
public int arith(int a, int b)
{
return(a*b);
55
}
}
class D extends C
{
public int arith(int a, int b)
{
return(a/b);
}
}
class FinalMethod
{
public static void main(String args[])
{
A p;
p=new B();
System.out.println(p.arith(10,20));
p=new C();
System.out.println(p.arith(10,20));
p=new D();
System.out.println(p.arith(10,2));
System.out.println(P4.arith(20,10));
}
}
If we make a class as final, we can’t create a sub class from final class.
final class A
{
public int arith(int a,int b)
{
return(a+b);
}
}
class B extends A
{
public int arith(int a, int b)
{
return(a+b);
}
}
56
8.10 ‘this’ keyword
The this keyword is used inside any instance method to refer to the current
object. The value of this refers to the object on which the current method has been
called. The this keyword can be used where a reference to an object of the current
class type is required.
Methods declared with the keyword static (class methods) cannot use this.
Program :
class A
{
private int a=10,b=20,c;
public void read()
{
this.a=25;
this.b=45;
}
public void sum()
{
c=a+b;
System.out.println(c);
}
}
class ThisDemo
{
public static void main(String args[])
{
A P1= new A ( ) ;
A P2= new A ( );
P1.read( );
P1.sum( );
P2.sum( );
}
}
OUTPUT :
70
30
57
9. Interface:
An Interface is a collection of methods without implementation. An
interface can also include variable declaration.
Interfaces are a close cousin to classes and their declaration resembling class
declarations.
interface interface-name
{
variables+methods;
}
Once an interface has been defined, one or more classes can implement that
interfaces. To implement the interface, include the implements keyword in a class
definition and then create a method defined by the interface.
Program :
interface A
{
public int sum(int a, int b);
}
class B implements A
{
public int sum(int a, int b)
{
return(a+b);
}
}
class InterfaceDemo1
{
public static void main(String args[])
{
B P=new B();
System.out.println(P.sum(20,10));
}
}
58
9.3 Multiple inheritance for creating Interface:
Note: If a class implements more than one interface, the interfaces are separated, in
this case we will get multiple inheritance.
Program:
interface A
{
public int sum(int a, int b);
}
interface B
{
public int mul(int a,int b);
}
interface C
{
public int diff(int a,int b);
}
}
}
One interface can inherit the another interface by using the keyword extends.
interface A
{
public int sum(int a,int b);
}
interface B extends A
{
public int mul(int a,int b);
59
}
interface C extends B
{
public int diff (int a , int b);
}
class D implements C
{
public int sum(int a,int b)
{
return (a+b);
}
public int mul(int a,int b)
{
return(a-b);
}
public int diff(int a,int b)
{
return(a-b);
}
}
class InterfaceDemo3
{
public static void main(String args[])
{
D P=new D( );
System.out.println(P.sum(20,10));
System.out.println(P.mul(20,10));
System.out.println(P.diff(20,10));
}
}
interface A
{
public int a=10;
public int b=20;
public int sum(int a, int b);
}
class B implements A
{
public int sum(int a, int b)
{
return(a+b);
}
}
class InterfaceDemo4
{
public static void main(String args[])
{
A P=new B();
System.out.println(P.sum(P.a,P.b));
}
}
60
61
10. Exception Handling
10.1 Introduction:
Advantages:
1. Separating Error Handling code from “Regular” code
2. Propagating Errors up the Call Stack
3. Grouping Error types and Error Differentiation
Class Hierarchy:
Object
Throwable
Error Exception
IOException RuntimeException
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42/d;
System.out.println(a);
System.out.println("End of program");
}
}
When a java run-time system detects the attempt to divide by zero, it
constructs a new exception object and then throws this exception. This cause the
excution of above program to stop, because once an exception has been throwns, it
must be caught by an exception handler and dealt with immediately.
62
Any exception that is caught by your program will ultimately processed by the
default handler. Hence default handler display a string describig the exception,
Java.lang.ArithmeticExcepiton : / by zero
Althoug the default exception handler provided by the java run-time system is
useful for debugging, you will usually want to handle an exception yourself. Doing so
provides two benefits.
To guard against the handle a run-time error, simply enclose the code that you want
to monitor inside a try block. Immediately following the try block, include a catch
clause that specifies the exception type that you wish to catch.
Program:
class ArithException
{
public static void main(String args[])
{
int a,b,c;
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a/b;
System.out.println( c );
}
catch(ArithmeticException e)
{
OUTPUT :
C:\> Java ArithException 100 0
Zero divide error.
63
Program:
import java.util.*;
class HandleError
{
public static void main(String args[])
{
int a=0, b=0, c=0;
Random r = new Random();
class ArrayException
{
public static void main(String arg[])
{
try
{
int a[]=new int[5];
a[0]=25;
a[1]=30;
a[2]=14;
a[3]=15;
a[4]=100;
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
System.out.println(a[5]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“You cannot access the value of
a[5]” + e);
}
}
}
64
c:\> java ArrayException
OUTPUT :
25
30
14
15
100
We cannot access the value of a[5].
class NegativeException
{
public static void main(String args[])
{
try
{
int a[]=new int [-5]
a[0]=26;
a[1]=14;
a[2]=15;
a[3]=40;
a[4]=100;
System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);
}
catch(NegativeArraySizeException e)
{
System.out.println(“Array size should be positive
integer”);
}
}
}
OUTPUT:
Array size should be a positive(+ve) no.(number)
class NumberException
{
public static void main(String args[])
{
try
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
65
c=a/b;
System.out.println(c);
}
catch(NumberFormatException e)
{
System.out.println(“Argument should contain only
numeric values”);
}
}
}
OUTPUT :
Java NumberException 100 er
10.2.5 FileNotFoundException :
10.2.7 UnKnownHostException :
class MultiCatch
{
public static void main(String args[])
{
int f=0;
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a/b;
System.out.println("Result = "+c);
}
catch(ArithmeticException e)
{
System.out.println("Zero divide error");
f=1;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Enter minimum two
arguements");
f=1;
}
catch(NumberFormatException e)
{
66
System.out.println("Cannot convert string to
integer");
f=1;
}
if(f==0)
System.out.println("Your Transcation is
completed ");
else
System.out.println("Your Transcation is not
completed ");
}
}
Note: Instead of having multiple catch block, we can use single catch block by
specifying simply Exception.
class SimpleException
{
try
{
}
catch (Exception e)
{
System.out.println(“Error”);
}
}
10.5 Throw:
Syntax:
class ThrowDemo
{
public static void main(String args[])
{
try
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
if(b==0)
throw new ArithmeticException();
else
{
c=a/b;
System.out.println( c );
}
}
catch(ArithmeticException e)
{
System.out.println(“zero divide error”);
System.out.println("Result ="+c);
}
}
67
10.6 Throws:
Syntax:
class WithoutThrows
{
public static void div(int a,int b)
{
int c;
c=a/b;
System.out.println( c );
}
public static void main(String args[])
{
div(20,0);
}
}
class WithThrows
{
public static void div(int a,int b)
throws ArithmeticException
{
int c;
c=a/b;
System.out.println("sum ="+c );
}
public static void main(String args[])
{
try
{
div(20,0);
}
catch(ArithmeticException e)
{
System.out.println("Error "+e);
}
}
}
68
10.7 Finally:
class FinallyDemo
{
public static void main(String args[])
{
int a=0,b=0,c=0;
try
{
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a/b;
}
catch(ArithmeticException e)
{
c=0;
System.out.println(“Error”+e);
}
finally
{
System.out.println( c );
}
}
Program:
import java.lang.*;
69
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
if(b== 0)
throw new CheckDivisor();
else
{
c=a/b;
System.out.println( c);
}
}
catch(CheckDivisor e)
{
System.out.println(“Error”+e);
}
}
}
70
11. Packages:
One of the biggest assets of JAVA is a rich library set is available. These libraries
include several pre-return methods and classes that can be used by everybody.
These libraries include classes and methods for IO operations, Mathematical
operations, Networking, Image processing and many more activities.
Depending on their functions, the classes in these libraries are grouped together &
called as packages.
The * at the end of the import statement indicates that all the classes of a given
package have to be imported. The second statement indicates that only the specified
class from the given package as to be imported. You can therefore import a
particular class or all the classes of a package using the import statement.
i. java.lang:
The java.lang package is one of the most important packages in Java. It provides
a no. of classes and interfaces that are fundamental to java programming.
71
Java.lang defines the following interfaces:
▪ Cloneable
▪ Comparable
▪ Runnable
1. parseByte(String str):-
Program :
class IntegerClass
{
public static void main(String args[])
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a+b;
System.out.println( c );
}
}
OUTPUT:
10
20
30
b. toBinaryString(int num):
Program:
class BinrayDemo
{
public static void main(String args[])
{
int num;
num = Integer.parseInt(args[0]);
System.out.println(Integer.toBinaryString(num));
}
}
10111
72
c. toHexString(int num):
System.out.println(Integer.toHexString(num));
OUTPUT: 30
1e
System.out.println(Integer.toOctalString(num));
Ouput 30
36
Note:
The Long Class also we can use to Binary String, toHexString, toOctalString
functions.
Program:
class FloatClass
{
public static void main(String args[])
{
float a,b,c;
a=Float.parseFloat(args[0]);
b=Float.parseFloat(args[1]);
c=a+b;
System.out.println( c );
}
}
OUTPUT :
16.3
30.5
73
11.3.5 The Double class:
double=Double.parseDouble(String s);
java.lang.Object
java.lang.Math
public final class Math extends Object
a) Sqrt( ) :
class SqrtDemo
{
public static void main(String args[])
{
double a,b;
a=Double.parseDouble(args[0]);
b=Math.sqrt(a);
System.out.println(b);
}
}
OUTPUT:
64
8.0
b) abs():
OUTPUT
-23
23
c) ceil():
OUTPUT
23.123
24
74
d) floor():
It returns the largest integer no. that are lesser than or equal to n.
Ouput
23.123
23
e) max(x,y):
class MaxDemo
{
public static void main(String args[])
{
double a,b,c;
a=Double.parseDouble(String args[0])
b=Double.parseDouble(String args[1])
c=Math.max(a,b);
System.out.println( c );
}
}
OUTPUT:
10 20
20
f) min(x,y):
g) exp(x):
h) log(x):
It returns the natural logarithm of given no.
i) sin(n):
It returns the sine of the angle specified by n in radians.
j) cos(n):
It returns the cos of the angle specified by n in radian.
k) tan(n):
It returns the tangent of the angle specified by n in radians.
75
Program:
class SinDemo
{
public static void main(String args[])
{
double a,b;
a=Double.parseDouble(args[0]);
a=a*3.14/180;
b=Math.sin(a);
System.out.println(b);
}
}
Degree to Radian:
Radian to degree 180/
/180
b=Math.asin(a);
b=b*/180
toRadians( ):
class RadianDemo
{
public static void main(String args[])
{
double a,b
a=Double.parseDouble(args[0]);
a=Math.toRadians(a);
b=Math.sin(a);
System.out.println(n);
}
}
toDegrees( ):
76
11.5 Character Class:
1. isDigit(ch):
Program:
class DigitDemo
{
public static void main(String args[])
{
char ch=’a’;
System.out.println(Character.isDigit(ch));
}
}
OUTPUT: false
77
12. String Class
12.1 Introduction :
When a String literal is used in the program, java automatically creates instances of
the String class. String are unusual in this respect.
Program:
class StringDemo
{
public static void main(String args[])
{
String str=new String("World computers");
//or
String str1=”World computer centre”;
System.out.println(str);
System.out.println(str1);
}
}
class StringLength
{
public static void main(String args[])
{
String str = ”World computer centre”;
System.out.println(str.length( ));
}
}
OUTPUT: 21.
12.3 indexOf(char):
This is method is used to search a String for a particular character & returns first
occurance of the character in the string. It returns –1 if the character is not found in
the string. It seen case sensitive.
{
String str= ”World Computer Centre”;
System.out.println (str.indexOf(‘o’));
}
OUPUT: 7.
78
12.4 lastIndexOf( char):
It returns the index of the last occurrence of the char in the string. It returns –1 if
the character is not found in the string.
The method searches for a string in the current object and returns the index value of
the first characters.
{
String str=”World Computer Centre”;
System.out.println(str.indexOf(“put”));
}
OUPUT: 9
{
String str = “World computer centre “
System.out.println(str.charAt(3));
}
OUTPUT : a
12.7 equals():
class EqualDemo
{
public static void main(String args[])
{
String str1=”World computer”;
String str2=”World computer”;
System.out.println(str1.equals(str2));
}
}
This method compare the strings with current object. It returns true if they are
equal and false if they are not equal.
12.8 equalsIgnoreCase()
This method is very similar to equals method, but as the name suggest, it ignores
the cases of the characters.
12.9 startsWith(startstring)
This method checks the current object starts with the same sequence of characters
as the string and returns true if it
79
class Startwith
{
public static void main(String args[])
{
String str = “World computer”;
System.out.println(str.startsWith(“World”));
}
}
OUPUT : true.
12.10 endsWith(endstring )
12.11 substring(i)
This method extracts a substring containing all the characters from the current object
starting from index ‘i’ till the end.
{
String str=”World computer”;
System.out.println(str.substring(7));
}
OUTPUT : computer
12.12 substring(i,j)
This method extracts a Substring starting from the index position ‘i’ up till the index
position j (Not including the upper in the jth position)
System.out.println(str.substring(7,10));
OUTPUT: omp
12.13 toLowerCase():
{
String str=”WORLD COMPUTER CETNRE”;
System.out.println(str.toLowerCase());
}
12.14 toUpperCase( ):
System.out.println(str.toUpperCase());
12.15 replace(ch1,ch2)
This method is used to replace all occurance of ch1, with another character ch2 in the
current object.
{
System.out.println(“World Computer Centre”);
System.out.println(Str.replace(‘a’,’e’));
}
OUTPUT : peler computer center
80
class Str
{
public static void main(String args[])
{
String str=new String("World computer");
//or
String str1="World computer";
System.out.println(str);
System.out.println(str1);
System.out.println("Length = "+str.length( ));
System.out.println ("Index Of o ="+str.indexOf('o'));
System.out.println("Index of put = "+str.indexOf("put"));
System.out.println("char at pos. 3 ="+str.charAt(3));
System.out.println("Str = str1 ="+str.equals(str1));
System.out.println("ignore Str = str1 ="+str.equalsIgnoreCase(str1));
System.out.println("Strat at World ="+str.startsWith("World"));
System.out.println("sub string of 7 = "+str.substring(7));
System.out.println("sub string of 7 to 10 = "+str.substring(7,10));
System.out.println("Lower Case = "+str.toLowerCase());
System.out.println("Upper case = "+str.toUpperCase());
System.out.println("Replace a to e = "+str.replace('a','e'));
System.out.println(str);
}
}
81
12.2 StringBuffer Class:
The original String remains unchanged during all the string manipulations performed
on it.
This is because, in Java, object of the String class, once created cannot be changed
(immutable).
In java StringBuffer class , the changes will affect the original string.
Program:
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer(“World computer”);
System.out.println(str);
}
}
OUTPUT : World computer
12.2.1 length( )
{
StringBuffer str=new StringBuffer(“World computer centre”);
System.out.println(str.length( ))
}
OUTPUT : 21
12.2.2 charAt(i)
0OUTPUT : World
12.2.3 append(char)
82
System.out.println(str.append("centre"));
System.out.println(str);
}
OUTPUT : World computers centre
12.2.5 insert(i,ch)
This method is used to insert a character ‘ch’ at the index position ‘i’.
{
StringBuffer str;
System.out.println(str.insert(7,’r’));
}
12.2.7 reverse( )
OUTPUT : ralap
12.2.8 setCharAt(i,ch)
The method replaces the char at index position ‘i’ in the String buffer with the
char ‘ch’.
{
StringBuffer Str=new StringBuffer(“World computer”);
Str.setCharAt(7,’r’);
System.out.println(str);
}
83
class StrBuff
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("World computer");
System.out.println(str);
System.out.println("Length = "+str.length( ));
System.out.println("Char at 2 is "+str.charAt(2));
System.out.println("Append s = "+str.append('s'));
System.out.println("Append Centre "+str.append(" centre"));
System.out.println("Insert r to 7th position =
"+str.insert(7,'r'));
System.out.println("Reverse "+str.reverse( ));
str.setCharAt(7,'z');
System.out.println("Set r to 7th poisition = "+str);
}
}
84
13. Java.util.package :
Collections Framework
A Collection is an object that groups multiple elements into a single unit. Collection
are used to store, retrieve and manipulate data, and to transmit data from one
method to another. It is at the top of the collections hierarchy (Base class)
Implementation (or classes are the actual data objects used to store the collections
1. AbstractCollection,
2. AbstractList,
3. AbstractSequentialList, Collection
4. ArrayList.
5. Arrays
6. LinkedList,
7. Stack,
8. Vector,
9. Date, Set List
10.AbstractSet,
11.HashSet,
12.Hashtable SortedSet
13.TreeSet etc.,
Algorithms are static methods within the Collection class. These method include
methods for sorting, searching, shuffling, data manipulations etc.
The legacy classes are Dictionary, HaseTable, Properties, Stack and Vector. The
legacy interface is the Enumeration Interface.
85
13.1 Util Interface
The List interface extends the Collection interface and declares the behavior of a
collection that stores a sequence of elements. Elements can be inserted or accessed
by their position in the list, using a zero-based index. A list may contain duplicate
elements
The Set interface extends the Collection interface and declares the behavior of a
collection that dose not allow duplicate elements. Therefore, the add ( ) method
returns false if an attempt is made to add duplicate elements to a set
The extension of the Set interface is the SortedSet Interface. It declares the
behavior of a set sorted in ascending order.
The ArrayList Class extends AbstractList and implements the List Interface.
ArrayList supports dynamic arrays that can grow as needed.
In java standard array are a fixed length is cannot be grown or shrink. That means
static array, know in advance how may elements are array will hold.
In essence, an ArrayList is a variable-length array of object references. ie, ArrayList
can dynamically increase or decrease in size. Array lists are created with an initial
size. When the size is exceeded, the collection is automatically enlarged. When object
are removed, the array may be shrunk.
1. ArrayList()
2. ArrayList(Collect c)
3. ArrayList(int capacity)
1. add(obj):
Insert obj into the invoking list at the end.
2. add(index,obj):
Insert obj into the invoking array list at the index passed in index.
3. remove(obj):
Removes one instance of obj from the invoking collection.
4. remove (index):
Remove a obj particular index.
5. size( ):
Returns the no. of elements of an array list.
86
Program:
// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
class ArrayListToArray
{
public static void main(String args[])
{
// Create an array list
ArrayList al = new ArrayList();
// get array
Object ia[] = al.toArray();
int sum = 0;
87
// sum the array
for(int i=0; i<ia.length; i++)
sum += ((Integer) ia[i]).intValue();
1. LinkedList()
2. LinkedList(Collection c)
1. add(obj):
Insert obj into the invoking linked list at the end.
2. add(index, obj):
Insert obj into invoking linked list at the index passed in index.
3. addFirst(obj):
Insert obj into the invoking linked list at the first end.
4. addLast(obj):
Insert obj into the invoking linked list at the last end.
5. remove(obj):
Removes the given element from the linked list.
6. removeFirst( ):
Removes the first element from the linked list.
7. removeLast( ):
Removes the Last element from the linked list.
8. getFirst( ):
Returns the 1st element of the linked list.
9. getLast( ):
Returns the Last element of the linked list.
10. size( ):
Returns the no. of elements of the linked list.
88
Program:
import java.util.LinkedList;
class LikedListDemo2
{
public static void main(String args[])
{
LinkedList l1=new LinkedList();
l1.add(“A”);
l1.add(“B”);
l1.add(“C”);
System.out.println(l1);
l1.add(1,”D”);
System.out.println(l1);
l1.addFirst(“E”);
System.out.println(l1);
l1.addLast(“F”);
System.out.println(l1);
l1.remove(“B”);
system.out.println(l1);
l1.removeFirst( );
System.out.println(l1);
l1.removeLast( );
System.out.println(l1);
System.out.println(l1.getFirst( ));
System.out.println(l1.getLast( ));
System.out.println(l1.size( ));
}
}
OUTPUT:
[A,B,C]
[A,D,B,C]
[E,A,D,B,C]
[E,A,D,B,C,F]
[E,A,D,C,F]
[A,D,E,F]
[A,D,C]
A
C
3.
Program:
// Demonstrate LinkedList.
import java.util.*;
class LinkedListDemo2 {
public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
89
ll.addFirst("A");
ll.add(1, "A2");
HashSet class extends AbstractSet and implements the Set interface. It creates a
collection that uses a hash table for storage. As most readers likely know, a hash
table stores information by using a mechanism called hashing. In hashing, the
information content of key is used to determine a unique value, called its hash
code.
The hash code is then used as the index at which the data associated with the key is
stored. The transformation of the key into its hash code is performed automatically,
you never see the hash code itself. Also, your code can't directly index the hash
table.
1. HashSet()
2. HashSet(Collection c)
3. HashSet(int capacity)
4. HashSet(int capacity, float fillRatio)
1. add()
2. contains(obj)
3. remove()
4. size()
90
Program:
// Demonstrate HashSet.
import java.util.*;
class HashSetDemo
{
public static void main(String args[])
{
// create a hash set
HashSet hs = new HashSet();
}
}
TreeSet provides an implementation of the Set Interface that uses a tree for
storage. Object are stored in sorted, ascending order. Access and retrieval times are
quite fast. Which makes TreeSet an excellent choice when storing large amount of
sorted information that must be found quickly.
1. TreeSet()
2. TreeSet(Collection c)
3. TreeSet(Comparator comp)
4. TreeSet(SortedSet as)
91
System.out.println(t1);
}
}
[D,E,K,P,R,Z]
[E,K,P,R,Z]
Program:
// Demonstrate TreeSet.
import java.util.*;
class TreeSetDemo2
{
public static void main(String args[])
{
// Create a tree set
TreeSet ts = new TreeSet();
System.out.println(ts);
}
}
Iterator enables you to cycle through a collection, for example, you might want to
display each element. By far, the easiest way to do this is to employ an Iterator,
obtaining or removing elements. ListIterator extends Iterator to allow bi-
directional traversal of a list, and the modification of elements.
Methods of Iterator
Methods Description
Boolean hasNext() Returns true if there are more elements, otherwise
returns false
Object next() Returns the next element. Throws
NoSuchElementException if there is not a next
element.
void remove() Removes the current element. Throws
IllegalStateException if an attempt is made to call
remove() that is not preceded by a call to next().
Method of ListIterator
Methods Description
void add(Object obj) Inserts obj into the list in front of the element tha
twill be returned by the next call to next()
Boolean hasNext() Returns true if there is a next element. Otherwise,
92
return false.
Boolean Return the index of the previous element. If ther is
hasPerviousIndex() not a previous element, return –1
Void set(Object obj) Assigns obj to the current element. This is the
element last returned by a call to either next() or
previous()
Program:
// Demonstrate iterators.
import java.util.*;
class IteratorDemo
{
public static void main(String args[])
{
// create an array list
ArrayList al = new ArrayList();
93
System.out.println();
}
}
Java 2 added a new class to java.util. called Arrays. This class provides various
methods that are useful when working with arrays. Although these methods
technically aren’t part of the collection framework, they help bridge the gap between
collections and arrays.
1. sort( ):
Program:
import java.util.*;
class BinaryArray
{
public static void main(String args[])
{
int a[]={90,25,10,30,15,60,95,100};
int i;
Arrays.sort(a);
for(i=0;i<a.length;i++)
{
System.out.println(a[i]+ “, “);
}
}
}
OUTPUT : 10,15,15,25,30,60,90,95,100
BinarySearch( ):-
This method used a binary search to find a specified value. This method must be
applied to sorted arrays.
Syntax:
Arrays.binarySearch(array,value);
import.java.util.*;
class ArraySort
{
public static void main(String args[])
{
int a[]={90,100,75,60,10,95,25,80};
int i ;
Arrays.sort(a);
System.out.println(Arrays.binarySearch(a,75));
}
}
OUTPUT 3.
3. equals( ): Equals method returns true if 2 arrays are equals otherwise it returns
false.
94
Program:
import java.util.*;
class ArrayEquals
{
public static void main(String args[])
{
int a[]={90,100,75,60};
int b[]={90,100,75,60};
System.out.println(Arrays.equals(a,b));
}
}
OUTPUT: True.
The original version of java.util did not included the collection framework. In
general, the legacy classes are supported because a large base of code exists that
uses them, including code still used by the java 2 API
▪ Dictionary
▪ HashTable
▪ Properties
▪ Stack
▪ Vector
The Enumeration interface defines the methods by which you can enumerate
(obtain one at a time) the elements in a collection of objects. This legacy interface
has been superceded by Iterator. Although not deprecated, Enumeration is
considered obsolete for new code.
1. Boolean hasMoreElements()
2. Object nextElement()
Methods Description
Boolean hasMoreElements() Returns true if there are more elements,
otherwise returns false
Object nextElement() Returns the next object in the enumeration as
generic object reference
95
3. Vector(int size, int incr) - specified size with specified increment
4. Vector(Collection c) - contains the elements of collection c
Program
class VectorDemo
{
public static void main(String args[])
{
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
96
/*for (Enumeration e = v.elements() ; e.hasMoreElements() ;)
{
System.out.println(e.nextElement());
}*/
}
}
13.5.2 HashTable Class:
It is used to create hash table. The hash table contains two columns. The 1 st column
is the index and the 2nd is value.
Program:
import java.util.*;
class HashTableDemo
{
public static void main (String args[])
{
Hashtable h=new Hashtable( );
h.put(“100”,”kumar”);
h.put(“101”,”Rangan”);
h.put(“102”,”Ram”);
h.put(“103”,”Sri”);
System.out.println(h.get(“102”));
System.out.println(h);
}
}
OUTPUT:
Ram
{103 Sri 102 Ram 101=Rangan 100=kumar}
Methods Description
boolean empty() Return true if the stack is empty, and return
false if the stack contains elements
Object peek() Returns the elements on the top of the stack,
but does not remove it
Object pop() Returns the element on the top of the stack,
removing it in the process.
Object push(Object element) Pushes element onto the stack. Element is also
returned
int search(Object element) Search for element in the stack. If found, its
offset from the top of the stack is returned.
Otherwise, -1 is returned.
97
Program:
class StackDemo
{
static void showpush(Stack st, int a)
{
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
StringTokenizer class provides the first step in this parsing process, prasing is the
division of text into a set of discrete part, or tokens, which in a certain sequence an
convey a semantic meaning.
StringTokenizer implements the Enumeration interface.
1. StringTokenizer(String str)
2. StringTokenizer(String str, String delimiters)
3. StringTokenizer(String str, String delimiters, Boolean delimAsToken)
98
Methods Description
int coutTokens() Using the current set of delimiters, the method
determines the number of token left to be parsed
and returns the result.
boolean hasMoreElement() Return true if one or more tokens remain in the
string and returns false if there are none.
boolean hasMoreToken() Returns true if one or more tokens remain in the
string and return false if here are none.
Object nextElement() Returns the next tokens as an Object
String nextToken() Returns the next token as String
String nextToken(String Returns the next token as String and sets the
delimiters) delimiters string to that specified by delimiters
Program:
// Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo
{
static String in = "title=Java: The Complete Reference;" +
"author=Naughton and Schildt;" +
"publisher=Osborne/McGraw-Hill;" +
"copyright=1999";
while(st.hasMoreTokens())
{
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}
The Date class encapsulates the current date and time. Date class is original version
of Java1.0. When Java1.1 was released, many of the functions carried out by the
original Date class were move into the Calendar and DateFormat classes, so many
of the Date methods are deprecated.
1. Date()
2. Date(Long millisecond)
99
Methods Description
boolean after(Date date) Returns true if the invoking Date object
contains a date that is later then the one
specified by date. Otherwise, it returns false.
boolean before(Date date) Returns true if the invoking Date object
contains a date that is earlier then the one
specified by date. Otherwise, it returns false
int compareTo(Date date) Compares the value of the invoking object with
(or) that of date. Return 0 if the values are equal.
int compareTo(Object obj) Returns a negative value if the invoking
objects is earlier than date. Return positive
value if the invoking object is later than date
Program:
class DateDemo
{
public static void main(String args[])
{
// Instantiate a Date object
Date date = new Date();
if(doj.after(dob))
System.out.println("Entry dates are correct ");
else
System.out.println("Pls. Enter Doj date after dob date ");
}
}
100
14. IO package :
The java.io.package provides Classes and Interfaces that supports for input and
output Operations.
import java.io.*;
class DataInputDemo
{
public static void main(String args[])throws IOException
{
DataInputStream ds=new DataInputStream(System.in);
String str;
int n1,n2,n3;
System.out.print(“Enter the first no:”);
str=ds.readLine( );
n1=Integer.parseInt(str);
System.out.println(“Enter the second no:”);
str=ds.readLine( );
n2=Integer.parseInt(str);
n3=n1+n2;
System.out.println(n3);
}
}
OUTPUT :
Enter the first no : 100
Enter the Second no: 200
300.
It is used to obtain or manipulate the information associated with a disc file, such as
a permission, directory path and so no.
1. getName( ):-
It returns the name of the file.
2. getParent( ):-
It returns the name of the parent directory.
3. exists( ):-
It returns true if the File exist, False if it does not the exist.
4. isFile( ):-
It returns true if it is a file And false if it is a directory.
5. isDirectory( ):-
It returns true if called on a directory. And false if called on a file.
101
6. canRead( ):-
This method is used to check whether the file s readable or not. If it is
readable then returns true otherwise it returns false.
7. canWrite( ):-
The method is used to check whether the file is writable or not.
8. isHidden( ):-
It returns true if the invoking file is hidden. Otherwise it returns false.
Program:
import java.io.*;
class FileDemo
{
static void P(String s)
{
System.out.println(s);
}
public static void main(String arg[])
{
File f1= new File("/subhjava/FileList.java");
P("File name : " + f1.getName());
P("Path : "+f1.getPath());
P("Abs Path : "+f1.getAbsolutePath());
P("Parent : "+f1.getParent());
P(f1.exists() ? "Exists " : "does not Exist ");
P(f1.canWrite () ? "is writeable " : "is not writeable");
P(f1.canRead () ? "is readable " :" is not readable");
P("is " + (f1.isDirectory() ? "directory ": "Not a
directory "));
P("is " + (f1.isHidden() ? "Hidden ": "Not Hidden"));
P(f1.isFile() ? "Normal file " : "might be a named pipe");
P(f1.isAbsolute () ? "is obsolute " : " is not absolute ");
P("File last modified : "+f1.lastModified());
P("file size : "+f1.length() + "Bytes");
}
}
import java.io.*;
class FileRename
{
public static void main(String args[])
{
File f1=new File(“c:/World/kumar”);
File f2=new File(“c:/World/prakash”);
f1.renameTo(f2);
}
102
}
import java.io.*;
class FileList
{
public static void main(String args[])
{
int i;
File f=new File(“e:/newjava”);
String str[]=f.list();
for(i=0;i<str.length;i++)
{
System.out.println(str[i]);
}
}
}
import java.io.*;
class MakeDirectory
{
public static void main(String args[])
{
File f1=new File(“c:\India”);
f1.mkdir();
}
}
13. delete( ):
It is used to delete the file (given).
import java.io.*;
class FileDelete
{
public static void main(String args[])
{
File f1=new File(“c:/India”);
f1.delete( );
}
}
103
14.3 Streams
• Byte Streams provide a convenient means for handling input and output of
bytes.
Bytes streams are used, for handling input and output of bytes
▪ InputStream
▪ OutputSream
The two most method important are read() and write(), which read and write bytes
of data.
▪ Reader
▪ Writer
The two most method important are read() and write(), which read and write
Characters of data.
104
14.4.2 The Character Stream I/O classes
import java.io.*;
class FileOpen
{
public static void main(String arg[]) throws IOException
{
FileInputStream fr = new FileInputStream(arg[0]);
int s;
while((s=fr.read())!=-1)
{
System.out.print((char)s);
}
fr.close();
}
}
import java.io.*;
class FileWrite
{
public static void main(String args[]) throws IOException
{
InputStreamReader kb=new InputStreamReader(System.in));
105
Program: Copying File From one to another
import java.io.*;
class FileCopy {
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
// open input file
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
}
// Copy File
try {
/* do {
i = fin.read();
if(i != -1)
fout.write(i);
} while(i != -1);*/
while((i=fin.read())!=-1)
fout.write(i);
} catch(IOException e) {
System.out.println("File Error");
}
fin.close();
fout.close();
}
}
106
15. User Defined Packages:
15.1 Packages
Package allows us to combine groups of classes and interfaces and also it controls
the accessibility of class inside a specific package.
Package provide protection to classes, variables and methods in larger way than on a
class-by-class basis.
Inside the directory create classes and compile all the classes
//package<directoryname>
package World;
public class Arith
{
public static int sum(int a,int b)
{
return(a+b);
}
public static int diff(int a,int b)
{
return(a-b);
}
public static int mul(int a,int b)
{
return(a*b);
}
public static int div(int a,int b)
{
return (a/b);
}
}
package World;
public class General
{
public int fact(int n)
{
int i, f=1;
for(i=1;i<=n;i++)
{
f=f*i;
107
}
return(f);
}
public int power(int x,int y)
{
int i,p=1;
for(i=1;i<=p;i++)
{
p=p*x;
}
return(p);
}
import World.*;
class AccessWorld
{
public static void main(String args[])
{
General g= new General();
System.out.println(Arith.mul(20,10));
System.out.println(g.fact(5));
}
}
OUTPUT :
200
120
108
16. Thread
16.1 Introduction
Unlike most other computer languages, java provides built-in support for
multithreaded programming. A multithreaded program conatins two or more parts
that can run concurrently
Each part of such a program is called a Thread, the each thread defines a
separate path of execution. Thus, multithreading is specialized form of multitasking.
However, there are two distinct types of multitasking: process-based and
thread-based.
A process having more than one thread is said to be multi threaded. A multi
threaded program is one in which these are two parts of same program that can run
concurrently.
109
1. By extending the Thread class :
Method Meaning
Program:
110
class World implements Runnable
{
public void run( )
{
try
{
System.out.println(“Welcome to java”);
Thread.sleep(3000);
System.out.println(“Welcome to World”);
}
catch(Exception e)
{
System.out.println(“Error”);
}
}
}
class RunnableDemo
{
public static void main(String args[])
{
Thread t1 = new World( );
t1.start();
}
}
111
class Third extends Thread
{
public void run( )
{
try
{
System.out.println(“Executing third thread”);
Thread.sleep(2000);
System.out.println(“End of third thread”);
}
catch(Exception e)
{
System.out.println(“Error”);
}
}
}
class MultiThread
{
public static void main(String args[])
{
First t1=new First( );
Second t2=new Second( );
Third t3 =new Third( );
t1.start( );
t2.start( );
t3.start( );
}
}
OUTPUT :
Executing First thread
Executing Second thread
Executing Third thread
End of first thread
End of third thread
End of second thread
The join method makes caller wait till the current thread finishes execution. In this
case it waits until the first thread finishes, before starting the second thread.
class JoinDemo
{
public static void main(String args[])
{
First t1=new First( );
Second t2=new Second( );
Third t3 =new Third( );
try
{
t1.start( );
t1.join( );
t2.start( );
t2.join( );
t3.start( );
t3.join( );
}
catch(Exception e)
112
{
System.out.println(“Error”);
}
}
}
OUTPUT :
Executing first thread
End of first thread
Executing second thread
End of second thread
Executing Third thread
End of third Thread
16.7 isAlive( ):
It is used to determine whether a thread has finished. The isAlive method returns
true if it is still running otherwise it returns false.
class AliveDemo
{
public static void main(String args[])
{
First t1=new First( );
Second t2=new Second( );
Third t3 =new Third( );
try
{
t1.start( );
if(t1.isAlive())
System.out.println("First Thread is running");
t1.join( );
if(t1.isAlive())
System.out.println(t1.isAlive( ));
else
System.out.println("First Thread finished");
t2.start( );
t3.start( );
}
catch(Exception e)
{
System.out.println(“Error”);
}
}
}
OUTPUT:
Executing first thread
true
End of first thread
False
Executing second thread
End of second thread
Executing third thread
End of third thread
113
16.8 Synchronization:
When two or more threads need access to a shared resources, they need some way
to ensure that the resource will be used by only one thread at a time. The process by
which this is called synchronization.
Example:
class Callme
{
synchronized void call(String msg)
{
System.out.print("[" + msg);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Interrupted");
}
System.out.println(" ]");
}
}
class Synch
{
}
}
114
17. Applet & Abstract Windowing Toolkit(AWT)
17.1 Applets:
▪ Java applications are simple stand-alone Java programs that can run using the
Java interpreter from the command line.
▪ Java applets run from inside a World Wide Web browser that supports java
applets.
Definition:
An applet is a dynamic and interactive program that can run inside a Web
page displayed by the Java-capable browser such as Hot-Java or Netscape and
Internet Explorer-Java Browser is World Wide Web Browser used to view Web
pages, follow links and submit forms. It can also download and play applets on your
system.
Java applets have restrictions to ensure security and to prevent them from being
affected by viruses. Some of restrictions are listed below.
Note: You can also run your applets in appletviewer tool, which is available in
JDK.
AWT includes rich set of user interface components,eg: label, button, textbox
etc.,and a powerful event handling model, graphics and image tools, layout
managers and support for data transfer using cut and paste throught clipboards.
AWT also supports Java Beans Architecutre. Every AWT component is a simple bean.
The java.awt package contains all classes for creating user interfaces and for painting
graphics and images.
The Awt has several subsystems that support the development of graphical user
Interface (GUI) programs. The subsystems include:
▪ Graphics package that allow drawing and rendering of lines and images
115
▪ Components such as Labels, Buttons and TextFields.
▪ Containers that include Frames, Panels and Dialogs.
▪ Layout managers that control the display in a portable manner.
▪ Event system, which allows the user to respond to interactions between the
components and containers in the applications.
import java.applet.Applet;
import java.awt.*;
public class AppletDemo extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Welcome to java applet”,100,100);
}
}
Syntax:
Appletviewer <filename>.htm.
HTML applet tag: The applet tag is used to start an applet from an applet viewer.
Code: Code is a required attribute that gives the name of the file containing your
applet’s compiled dot class file.
Width and Height: Width and Height are required attributes that give the size of
the applet display area.
drawString ()
116
Here message is the string to be output beginning at x, y.
The java. applet. Applet includes five methods that are frequently used while
writing applets. They are init ( ), start( ), stop( ), destroy( )
Init method()
The init() method is executed only once at the start of applet execution.
Initialization of all variables, creation of objects, setting of parameters, ect. Can be
done in this method. So it typically includes code that needs to be executed once
when the applet starts executing.
Start() Method
This method is executed after the init() method. in case a java enabled browser is
used to run the applet, any time it is reloaded, the execution begins from the start()
method.
Stop method()
The stop() method is used to halt the running of an applet. In case the Java enabled
browser is used to run the applet, the stop() method is called the moment the Web
page is exited.
The 2nd and 4th method start and stop are normally used in conjunction to start,
then temporarily stop and again restart the applet execution (Minimize → stop ,
Maximize-start). Both these methods can be called several times in the applet.
This stop method is automatically invoked when the applet window is minimized.
Similarly the start is invoked when the applet viewer window is maximized.
This method helps in drawing, writing and creating a colored background or an image
onto the applet. It takes an argument, which is an instance of the Graphics class.
To use this method, it is necessary to import the Graphics class on import
java.awt.Graphics.
This method is used to free the memory occupied by the variables and objects
initialized in the applet. Any clean up activity that needs to be performed can be done
in this method.
This method is used in case an applet is to be repainted. The repaint() calls the
update() method, to clear the screen of any existing content. The update() method
in turn calls the paint() method that then draws the contents of the current frame.
Repaint can be done mentioning time in milliseconds to performed in future. If the
time expires before update() can be called, update is not summoned.
117
repaint( ) update( )
paint( )
Program:
import java.awt.*;
import java.applet.*;
public class AppletLifeDemo extends Applet
{
public void init( )
{
System.out.println(“Executing init method”);
}
public void start( )
{
System.out.println(“Executing start method”);
}
public void paint(Graphics g)
{
g.drawString(“welcome to java”,100,100);
}
public void stop( )
{
System.out.println(“Executing stop method”);
}
public void destroy( )
{
System.out.println(“Executing destroy method”);
}
}
1. SetBackground( )
Syntax:
setBackground(Color obj);
2. SetForeground( )
To set the fore ground color (Text color) use text color.
setForeground(Color obj);
118
17.5 Colors in java
Program:
import java.applet.*;
import java.awt.*;
public class AppletColorDemo extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.pink);
setForeground(Color.blue);
g.drawString(“Welcome To Java Applet”,100,100);
}
}
Syntax:
import java.awt.*;
import java.applet.*;
//<applet code=AppletColor width=300 height=300 ></applet>
public class AppletColor extends Applet
{
public void paint(Graphics g)
{
Color c1=new Color(255,34,67);
Color c2=new Color(255,0,0);
setBackground(c1);
setForeground(c2);
g.drawString(“welcome to Java”,100,100);
}
}
119
showStatus( )
In addition to displaying information in its window, can also output a message to the
status window of the browser or applet viewer on which it is running. To do so call
showStatus with the String that you want displayed.
17.6.1Drawing lines:
It displays a line in the current drawing color that begins at x1, y1 and ends at x2
and y2.
Program :
import java.awt.*;
import java.applet.*;
public class AppletDraw1 extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.pink);
g.drawLine(100,100,150,200);
}
}
OUTPUT :
The drawRect and fillRect methods displayed an outlined and filled rectangle
respectively.
Syntax:
120
The upper-left corner of the rectangle is at x1,y1, the dimensions of the rectangles
rounded rectangle, use drawRoundRect and fillRoundRect.
Syntax:
drawRoundRect(int x1,int y1, int width, int height, int x1dia,int y1dia);
fillRoundRect(int x1,int y1,int width,int height,int x1dia,int y1dia);
A rounded rectangle has rounded corners. The upper-left corner of the rectangle is at
x1, y1. The dimension of the rectangle are specified by width and height. The
diameter of the rounding are along the x-axis is specified by x.dia. The diameter of
the rounding are along the y-axis is specified by y.dia.
Program:
import java.awt.*;
import java.applet.*;
public class AppletDraw2 extends Applet Output :
{
public void paint(Graphics g)
{
g.setColor(Color.pink);
g.drawRect(50,50,50,20);
g.setColor(Color.red);
g.fillRect(100,100,50,20);
g.setColor(Color.blue);
g.drawRoundRect(150,150,50,20,5,55);
g.setColor(Color.green);
g.fillRoundRect(200,200,50,20,5,5);
}
}
Syntax:
The ellipse is drawn within a bounding rectangle whose upper left corner is specified
by x1,y1 and whose width and height.
import java.awt.*;
import java.applet.*;
public void paint(Graphics g) O/p:
{
g.setColor(Color.blue);
g.drawOval(100,100,200,200);
}
121
17.6.4 Drawing Arcs:
Syntax:
drawArc(int x1,int y1, int width, int height, int start.angle, int end.angle);
fillArc(int x1,int y1, int width, int height, int start.angle,int end.angle)
The arc is bounded by the rectangle whose upper left corner is specified by x1,y1 &
whose width & height are specified by width and height. The arc is drawn from start
angle through the angular distance specified by end angle.
Angles are specified in degrees.
Program:
Syntax:
DrawPolygon(int x[ ], int y[ ], int no. of points);
The Polygon’s end points are specified by co-ordinate pairs contained within the x
and y arrays.
Program:
The awt supports multiple type of fonts. The awt provides flexibility by abstracting for
dynamic selection of fonts.
To select a new font, you should first consider the font object that describes that
font.
Syntax:
Here font name specifies the name of the font. The style of the font is specified by
font style. It may consist of one or more of these three constants.
122
Font.PLAIN, Font.BOLD,Font.ITALIC.
The size in points of the font is specified by font size.
To use a font that you have created, you must select it using set font.
Program:
import java.awt.*;
import java.applet.*;
public class AppletFont extends Applet
{
public void paint(Graphics g)
{
Font f=new Font(“Arial”,Font.BOLD+Font.ITALIC,25);
g.setFont(f);
g.setColor(new Color(255,0,255));
g.drawString(“Welcome to Java”,150,150);
}
}
17.8 Images:
import java.applet.Applet;
import java.awt.*;
public class ImageDemo extends Applet
{
Image img;
public void init()
{
img=getImage(getCodeBase(),"image.jpg");
}
public void paint(Graphics g)
{
g.drawImage(img,10,10, this);
}
}
123
18. Event Handling
The user communicates with window programs by performing actions such as
clicking a mouse botton or pressing a key on the keyboard. These actions result in
the generating of events. The process of responding to an event is known as Event
Handling. Window program are said to be event-driven because they operate by
performing actions in response to events.
The event delegation approach is less complex and more efficient. It uses
special classes called adapter classes, whose objects listen for the occurance of
events on behalf of objects of other classes.
Each event is represented by an object that gives information about the event and
identifies the event source. Event sources are typically components, but othe kinds
of objects can also be event soruces.
1. In the declaration for the event handler class, code that specifies that the
class either implements a listener interface or extands a class that implements
a listener interface. For example
2. code that registers an instance of the event handler class as a listener upon
one or more components. For example
Syntax:
somecomponent.addActionListener(instanceof Myclass);
Eg:
obj.addActionListener(this);
3. code that implements the methods in the listener interface. For example
124
public void actionPerformed(ActionEvent e)
{
//code that reacts to the action….
}
1. MouseListener interface
2. MouseMotionListener interface
1. MouseListener Interface:
1. Mouse Clicked: This method is invoked when the mouse is pressed and
released at the same point.
2. MousePressed: This method is invoked when the mouse is pressed.
3. Mouse Released: This method is invoked when the mouse is released.
4. Mouse Entered: This method is invoked when the mouse entered into the
appletviewer.
5. Mouse Exited: This method is invoked when the mouse exited from the
applet viewer.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDemo extends Applet implements MouseListener
{
String msg;
public void init( )
{
addMouseListener(this);
}
public void mouseClicked (MouseEvent me)
{
msg=”Mouse clicked”;
repaint( );
}
public void mousePressed (MouseEvent me)
{
msg=”Mouse pressed”;
repaint( );
}
public void mouseReleased (MouseEvent me)
{
msg=”Mouse Released”;
repaint( );
}
public void mouseEntered (MouseEvent me)
{
msg =”Mouse Entered”;
125
repaint( );
}
public void mouseExited (MouseEvent me)
{
msg = “Mouse Exited “;
repaint( );
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}
2. MouseMotionListener interface:
Program:
Program:
126
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class KeyboardDemo extends Applet implements KeyListener
{
String msg;
public void init( )
{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
msg=”Key Pressed”;
repaint( );
}
public void keyReleased(KeyEvent ke)
{
msg = “Key Released”;
repaint();
}
public void keyTyped(KeyEvent ke)
{
msg = “Key Typed”;
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}
127
19. AWT Controls:
19.1 User Interface Components:
A place in which the various drawing needs to be done must be provided and this is
called the container. The container is derived from java.awt.Container class. The
elements of the Userinface are called components. These components are derived
from the java.awt.Component class.
All the user interface components and container classes are derived from this class.
There are two major set of classes derived from the component class:
▪ The Container Classes - they are generic AWT components that can contain
other components
Controls are components that allow a user to interact with your application in various
base.
Applet
Panel
Dialog
The AWT package contains a number of component classes that are typical elements
Frame
Button
Checkbox
Object Component
TextArea
Text Component
TextField
Choice
List
Label
128
of any interactive user interface. These classes are derived from the abstract
Compoenent class. The figure shows the class hierarchy of these classes.
The Component class define a number of methods that can be used on any of the
classes that are derived from it. The methods listed below in table can be used on all
UI compoents as well as containers.
Methods Description
setSize(Dimension d) Resizes the corresponding component so that it has
width d.width and height d.height
setSize(int width, int Resizes the corresponding component so that it has
height) width and height
setFont(font f) Sets the font of the corresponding component
setEnabled(Boolean b) Enables or disables the corresponding component,
depending on the value of the parameter b.
setVisible(Boolean b) Shows or hides the corresponding component
depending on the value of prarament b.
setForground(Color c) Set the foreground color of the corresponding
component.
setBounding(int x, int y, int Moves and resizes the corresponding component.
width, int height)
setBounds(Rectangle r) Moves and resizes the corresponding component.
To conform to the new bounding rectangle r.
setBackground(Color c) Set the background color of the corresponding
component.
getBackground() Gets the background color of the corresponding
component.
getBounds() Get the bound sof the corresponding component in
the form of a Rectangle object
getFont() Gets the font of the corresponding component.
getForeground() Gets the foreground color of the corresponding
component.
getSize() Return the size of the corresponding component in
the form of a Dimension object.
19.2.1. Labels:
Syntax:
Program:
import java.awt.*;
import java.applet.*;
public class LabelDemo extends Applet
{
public void paint(Graphics g)
{
Label l1=new Label (“World”);
Label l2=new Label (“Vellore”);
add(l1);
129
add(l2);
}
}
19.2.2 Button:
The most widely used control is Button. A button is a component that contains a
label and that generates a event when it is pressed.
Each time a button is pressed, an action event is generated to access action event,
we have to create ActionListener interface. That interface defined the
actionPerformed() method which is called when an event occurs. A Label is
obtained by getActionCommand() method.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ButtonDemo extends Applet implements ActionListener
{
public void init( )
{
Label l1=new Label (“Click to Select Colors and set
BackGround”);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand( );
if(str.equals(“Red”))
setBackground(Color.red);
else if(str.equals(“Green”))
setBackground(Color.green);
else if(str.equals(“Blue”))
setBackground(Color.blue);
else if(str.equals(“Pink”))
setBackground(Color.pink);
130
else if(str.equals(“Black”))
setBackground(Color.black);
else
setBackground(Color.white);
}
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TextFont extends Applet implements ActionListener
{
Font f;
public void init( )
{
Button b1=new Button (“Times New Roman”);
Button b2 =new Button (“Arial”);
Button b3= new Button(“Arial Black”);
Button b4=new Button(“Courier New”);
Button b5=new Button(“Comic Sans MS”);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListenter(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand( );
f= new Font(str,Font.BOLD,20);
repaint( );
}
public void paint(Graphics g)
{
g.setFont(f);
g.drawstring(“World Computers”,100,100);
}
}
131
19.2.3 Text Field:
The textfield class implements a single line text entry area, usually called an edit
control.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TextDemo extends Applet implements ActionListener
{
TextField t1,t2;
Label r;
public void init( )
{
Label l1=new Label("Enter the 1st no: ");
Label l2=new Label("Enter the 2nd no: " );
Label l3=new Label("Result");
t1 = new TextField(10);
t2 = new TextField(10);
r = new Label(" ");
Button b1 = new Button("SUM");
Button b2 = new Button("SUB");
Button b3 = new Button("DIV");
Button b4 = new Button("MOD");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(r);
add(b1);
add(b2);
add(b3);
add(b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str,str1;
str=ae.getActionCommand();
str1 =t1.getText( );
int n1=Integer.parseInt(str1);
str1 = t2.getText( );
int n2= Integer.parseInt(str1);
int n;
if(str.equals("SUM"))
{
n=n1+n2;
r.setText(n+"");
}
132
else if(str.equals("SUB"))
{
n=n1-n2;
r.setText(n+" ");
}
else if(str.equals("DIV"))
{
n=n1/n2;
r.setText(n+" ");
}
else if(str.equals("MOD"))
{
n=n1%n2;
r.setText(n+" ");
}
}
}
Note: There may be times when you want the user to enter text should not
displayed, example, for password field You can display the other characters (*)
common for alphabets
133
setEchoChar.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class SetEchoDemo extends Applet implements ActionListener
{
TextField t1,t2;
String msg;
public void init();
{
Label l1= new Label (“User name”);
Label l2= new Label(“Password”);
t1 =new TextField(10);
t2= new TextField(10);
t2.setEchoChar(‘*’);
Button b1 = new Button(“Login”);
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str1=t1.getText( );
String str2= t2.getText( );
if(str1.equals(“World”) && str2.equals(“admin”))
msg=”User name and password are correct”;
else
msg=”invalid username or password”;
repaint( );
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}
19.2.4 TextArea:
Sometimes a Single line of text i/p is not enough for a given task. To handle these
situations, AWT includes a Simple multiline editor called TextArea.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TextAreaDemo extends Applet
{
public void init( )
{
TextArea t1= new TextArea(10,15);
add(t1);
134
}
}
19.2.5 Checkboxes:
It creates a check box whose label is specified by str (string). Each time a
checkbox is selected or deselected, an itemEvent is generated. To access ItemEvent
we have to implement ItemListener interface. That interface defines the
itemStateChanged method. getState returns the status of the checkbox. If we
selected the checkbox, it returns true. If we deselect the checkbox, it returns false.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
135
19.2.6 Checkbox Group:
It is possible to create a set of mutually execute checkboxes in which one and only
one check box in a group can be checked at any one time. These checkboxes are
often called Radio buttons. To create a set of mutually exclusive checkboxes, we
must first define the group to which they will belong and then specify the group when
you construct the checkboxes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class CheckDemo1 extends Applet implements ItemListener
{
CheckboxGroup cbg;
Checkbox c1,c2,c3,c4,c5;
public void init( )
{
cbg= new CheckboxGroup( );
c1= new Checkbox(“Red”,cbg,false);
c2= new Checkbox(“Green”,cbg,false);
c3= new Checkbox(“Blue”,cbg,false);
c4= new Checkbox(“Pink”,cbg,false);
c5= new Checkbox(“Magenta”,cbg,false);
add(c1);
add(c2);
add(c3);
add(c4);
add(c5);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
if(cbg.getSelectedCheckbox( ) == c1)
setForeground(Color.red);
else if (cbg.getSelectedCheckbox( ) == c2)
setForeground(Color.green);
else if (cbg.getSelectedCheckbox( ) == c3)
setForeground(Color.blue);
else if (cbg.getSelectedCheckbox( ) == c4)
setForeground(Color.pink);
else
setForeground(Color.magenta);
repaint( );
}
public void paint(Graphics g)
{
136
Font f= new Font("Arial",Font.BOLD,25);
g.setFont(f);
g.drawString(“World Computer Centre”,100,100);
}
}
The Choice class is used to create a pop-up of list of items from which the user may
choice. When inactive, a choice component takes up only enough space to show the
currently selected item. When the user clicks on it, the whole list of choices pops up
and a new selection can be made.
To add a selection to the list, call add. To determine which items is currently
selected we have to use which items is currently selected we have to use
getSelectedItem method. It returns a string containing the name of the item. To
access choice control we have to use ItemListener interface.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ChoiceDemo extends Applet implements ItemListener
{
Choice c;
public void init( )
{
c = new Choice();
c.add(“Red”);
c.add(“Green”);
c.add(“Pink”);
c.add(“Blue”);
c.add(“Gray”);
add (c);
c.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
String str=c.getSelectedItem( );
if(str.equals(“Red”))
setBackground(Color.red);
else if (str.equals(“Green”))
setBackground(Color.green);
else if(str.equals(“Pink”))
setBackground(Color.pink);
else if (str.equals(“Blue”))
setBackground(Color.blue);
else
setBackground(Color.gray);
}
}
137
19.2.8 List Controls:
The list class provided a compact scrolling selection list unlike the choice object,
which shows only the single selected item in the menu, a list object can be
constructed to show any number of choices in a visible window.
Here, the value of numRows specifies the no. (number) of entries in the list that will
always be visible(others can be scrolled into view as needed). To add a selection to
the list, call add method. The getSelectedItem method returns a String containing
the name of the item. To process the list, we have to implement itemListener
interface.
Program:
import java.awt.*;
import java.awt.event.*;
public class ListDemo extends Applet implements ItemListener
{
List l;
public void init( )
{
l = new List (4);
l.add(“Red”);
l.add(“Green”);
l.add(“Pink”);
l.add(“Gray”);
l.add(“Magenta”);
l.add(“Blue”);
add (l);
l.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
String str=l.getSelectedItem( );
if(str.equals(“Red”))
setBackground(Color.red);
else if (str.equals(“Green”))
setBackground(Color.green);
else if (str.equals(“Pink”))
setBackground(Color.pink);
else if (str.equals(“Gray”))
setBackground(Color.gray);
else if (str.equals(“Magenta”))
setBackground(Color.magenta);
else
setBackground(Color.blue);
}
}
138
20. Layout Management
The Layout Management classes are a set of classes that implement the
java.awt.LayoutManger interface and help to position the components in a container.
The interface takes the task of laying out the child components in the container.
Resizing and moving the child components achieve this task. The advantage of this
type of mechanism is that when the container is resized the layout manager
automatically updates the interfaces.
1. FlowLayout
2. BorderLayout
3. GridLayout
4. GridBagLayout
5. CardLayout
The next step is to associate the layout manager with the container on which it
should operate. The method setLayout() sets the layout manager of a container.
Once the layout manger for the container is set, components added to it will be
arranged depending on the layout specified.
20.1 FlowLayout
The FlowLayout class is simple layout manager that works like a word processor.
Components are displayed with their preferred size in order in which they are added
to the container. The flow layout lays out components lineswise from left the right.
When the line of components is filled, flow layout creates a new line and continues
laying out components on the next line. Like a word processor a FlowLayout+
FlowLayout Constructors:
Constructor Description
FlowLayout() Constructs a new flowlayout with centered
alignment, leaving a vertical and horizontal
gap of 5 pixels
FlowLayout(int align) Constructs a new flowlayout with the
alignment specified leaving a vertical and
horizontal gap of 5 pixels
FlowLayout(int align, int vgap, int Constructs a new flowlayout with the
hgap) alignment specified, leaving a vertical and
horizontal gap of 5 pixels
139
The various methods that can be used in combination with the flow layout is given
below.
Methods Description
getAlignment() Gets the alignment for the layout
getHgap() Gets the horizontal gap between components
getVgap() Gets the vertical gap between components
setAlignment(int align) Sets the alignment for the special layout.
setHgap(int hgap) Set the horizontal gap for the specified layout
setVgap(int vgap) Set the vertical gap for the specified layout
Program:
import java.awt.*;
}
}
The GridLayout class lays out components in a way very similar to a spreadsheet in
rows and columns. Specifying the number of rows and columns in the grid creates
the GridLayout. The components in a grid are resized of fit their cell. All components
in a grid layout are of the same size. The position of component in a grid is
determined by the order in which the components are add to the grid. Component
are display from left to right and top to bottom.
The grid layout can be constructed using the constructors listed below
Constructors Description
GridLayout() Creates a grid layout with a default of one
column per component in a single row
GridLayout(int rows, int cols) Creates a grid layout with the specified rows
and columns.
GridLayout(int rows, int cols, Creates a grid layout with the specified rows
int hgap, int vgap) and columns and specified horizontal and
vertical gaps.
The various methods that can be used in conjunction with the gird layout are listed
below
140
Methods Description
getColumns Gets the number of Columns in the layout
getRows() Gets the number of Rows in the layout
getHgaps() Gets the horizontal gaps for the layout
getVgap() Get the Vertical gaps for the layout
getColumns(int cols) Sets the number of columns in the layout
getRows(int rows) Sets the number of rows in the layout
Program:
import java.awt.*;
The BorderLayout class enables specification, ie., where on the border of a container
each component should be palced. All areas need not be filled. The size of the areas
will depend on the components they contain.
With border layout, the placement of the components is specified as being, North,
South, East and West. The border layout resizes the Center component ot fill the
remaining center space.
The various constructors that can be used to create a border layout is given below.
Constructors Description
BorderLayout() Creates a new border layout with no gap
between the components
BorderLayout(int hgap, int vgap) Creates a new border layout with the
specified horizontal and vertical gap
between components.
The various methods that can be used in conjuction with the border layout is given
below.
Methods Description
getHgap() Returns the horizontal gap between components
getVgap() Returns the Vertical gap between components
setHgap() Set the horizontal gap between components to the value
specified.
setVgap() Set the vertical gap between components to the value
specified.
141
Eg: add("East",mybutton);
Program:
import java.awt.*;
Insets:
20.4 CardLayout:
The CardLayout allows only one of its components to be visible at a time. The
CardLayout considers each of its components as a card. The CardLayout is controlled
by a combo box. The state of the combo box determines with panel is displayed by
the CardLayout. Using the CardLayout, the user has the option to view the following
Constructors Description
CardLayout() Creates a new card layout whose gaps are
of size zero.
CardLayout(int h, int v) Creates a new card layout with the
horizontal gap and vertical gap
142
The methods are:
Methods Description
First(Container c) Display the first card of the container c
Last(Container c) Display the Last card of the container c
Next(Container c) Display the Next card of the container c
Previous(Container c) Display the Previous card of the container c
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
143
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==Win)
{
cardLO.show(osCards,"Windows");
}
else
{
cardLO.show(osCards,"Other");
}
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class NewResult extends Applet implements ActionListener
{
TextField t1,t2,t3,t4;
Label t,a,g,r,head;
Panel p1,p2,p3,h;
public void init()
{
Font f= new Font("Arial",Font.BOLD,20);
head = new Label("Result Sheet");
head.setFont(f);
head.setForeground(Color.blue);
h = new Panel();
h.setLayout(new FlowLayout());
h.add(head);
p1=new Panel();
p1.setLayout(new GridLayout(4,2));
p1.add(l1);
p1.add(t1);
p1.add(l2);
p1.add(t2);
p1.add(l3);
144
p1.add(t3);
p1.add(l4);
p1.add(t4);
p1.add(l5);
p1.add(t);
p1.add(l6);
p1.add(a);
p1.add(l8);
p1.add(r);
p1.add(l7);
p1.add(g);
p2=new Panel();
p2.setLayout(new FlowLayout(FlowLayout.CENTER));
p2.add(b1);
p3=new Panel();
p3.setLayout(new GridLayout(3,1));
p3.add(h);
p3.add(p1);
p3.add(p2);
add(p3);
p3.setBounds(20,20,200,200);
b1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String s=t2.getText();
int m1=Integer.parseInt(s);
s=t3.getText();
int m2=Integer.parseInt(s);
s=t4.getText();
int m3=Integer.parseInt(s);
int t=m1+m2+m3;
float a=Math.round((float)t/(float)3.0);
System.out.println(a);
String strtot=new String(t+"");
strtot.trim();
System.out.println(strtot);
char chtot[];
chtot=strtot.toCharArray();
StringBuffer str = new StringBuffer();
int i=0;
System.out.println("Printing in words ....");
try
{
while(i<chtot.length)
{
System.out.println(chtot[i]+"");
switch(chtot[i])
{
case '1': str.append(" One");
break;
case '2': str.append(" Two");
break;
case '3': str.append(" Three");
break;
case '4': str.append(" Four");
break;
case '5': str.append(" Five");
break;
case '6': str.append(" Six");
145
break;
case '7': str.append(" Seven");
break;
case '8': str.append(" Eight");
break;
case '9': str.append(" Nine");
break;
case '0': str.append(" Zero");
break;
}
i++;
}
}
catch(Exception e1){ }
this.t.setText(t+" "+str);
this.a.setText(a+"");
System.out.println(str);
if(m1>=40 && m2>=40 && m3>=40)
{
r.setText("Pass");
if(a>=75)
g.setText("Distinction");
else if(a>=60)
g.setText("First Class");
else if(a>=40)
g.setText("Second Class");
}
else
{
r.setText("Fail");
g.setText("No grade");
}
}
}
Adapter Class
Most listener interfaces contain more than one method. For example the
MouseListener interface contains five methods: Even if you care only about mouse
clicks, if your class directly implements mouselistener, then you must implements all
five mouselistener methods. Methods for those events you don't care about can have
empty bodies.
The API generally includes an adapter class for each listener interface with more than
one method. For example, the MouseAdapter class implements the MouseListener
interface. An adapter class implements empty versions of all its interfaces methods.
146
…………..
someobject.addMouseListener(this);
…………
public void mouseClicked(MouseEvent e)
{
……
//Event handler implementation goes here
……….
}
}
Program for Adapter Class and Nested Class
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
147
++num;
}
}
}
Summary:
148
22. Frames and Menu
22.1 Frames:
The Frame class is used to create standard application windows. The Frame window
is a full-fledged window by itself that can contain the following user interface
elements. i.e the separate pop-up window their own files, Resides angles and menu
bars.
1. Title bar
2. Menu Bar
3. Control Elements - these are UI components that are added to the Frame
using the add() method of the Container.
Constructors Description
Frame() Creates a title frame, which is initially invisible
Frame(String) Creates a fram with the String as the title.
Unlike Panels, a Frame object is rarely created directly from the applet. Since the
frame is a separate pop-window, the events generated by the UI element in the
frame are not sent to the applet. Instead, these events are sent to Frame object.
To handle these events, the Frame class should be customized by deriving a sub-
class from it. This sub-class can have all event handlers specific to the problem.
Methods Description
setVisible(Boolean) Makes the frame or window visible
setSize(Dimension) Resizes the frame to the specified width and
height
setLocation(int, int) Moves the frame to the specified coordinates.
getLocation() Returns the current coordinates of the Frame as
a points object. In case of top level windows like
frames the location is in screen coordinate
system.
149
The Frame class also provide methods that allows getting and setting the title of the
Frame and other methods are listed below.
Methods Description
getTitle() Returns the title of the Frame as a String
setTitle(String) Changes the title of the Frame to the
specified String.
dispose() Releases all the resources related to the
window. The window is removed from the
screen.
When the user attempts to close the frame an event, with id WINDOW CLOSING
event type is generated. The customized frame class should handle this event to
dispose the frame.
Program:
import java.awt.*;
import java.awt.event.*;
150
{
MyText mf=new MyText ();
mf.setSize(300,300);
mf.setVisible(true);
}
}
22.2 Panel:
The Panel class in a non-abstract, recursively nestable, container. The panel can
contain UI components or other containers.
The add() method of the Container class can be used to add a component to the
panel.
p1.add(myButton);
Like all containers, the layout of the Panel can be set using the setLayout() method
22.3 Menus
A menubar displays a list of top-level menu choice. Each choice is associated with a
drop-down menu. This concept is implemented in Java by the following classes.
1. MenuBar
2. Menu
3. Menu Item
In general a menuBar contains one or more menu objects. Each objects contains
a list of menu items. Each menu item represents something that can be selected by
the user.
3. create instances of menu that will deifned the selection displaced on the
menubar.
Syntax: Menu obj =new Menu (String option name);
4. create instances of menu item.
Syntax: MenuItem obj =new MenuItem (String option name);
5. Once you have created a menu item, you must add the item to a menu
object by using add.
6. Once you have added all items to a menu Object, you can add menu that
object to the menu bar using add.
7. Once you have added all menus to a menu bar, you can add menu bar to the
frame using setMenuBar( ).
8. Menus only generate events when an item of type menu is selected. They do
not generate events when a menu bar is accessed to display a drop-down
151
menu. Each time a menu item is selected, an actionevent is generated.
Thus you must implement ActionListener interface.
Program:
import java.awt.*;
import java.awt.event.*;
file.add(f1);
file.add(f2);
file.add(f3);
file.add(bar);
file.add(f4);
file.add(f5);
file.add(f6);
edit.add(e1);
edit.add(e2);
edit.add(e3);
color.add(c1);
color.add(c2);
color.add(c3);
color.add(c4);
color.add(c5);
mbr.add(file);
mbr.add(edit);
mbr.add(color);
setMenuBar(mbr);
152
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals(“Red”))
setBackground(Color.red);
else if(str.equals(“Green”))
setBackground(Color.green);
else if(str.equals(“Blue”))
setBackground(Color.blue);
else if(str.equals(“Pink”))
setBackground(Color.pink);
else
setBackground(Color.magenta);
}
}
class MenuDemo
{
public static void main(String args[])
{
Myframe mf = new Myframe( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
Program:
import java.awt.*;
import java.awt.event.*;
class MyMenu extends Frame implements ActionListener
{
Font f;
MyMenu ( )
{
super(“Font Menu”);
MenuBar mbr=new MenuBar( );
153
MenuItem e1 = new MenuItem(“cut”);
MenuItem e2 = new MenuItem(“copy”);
MenuItem e3 = new MenuItem(“paste”);
color.add(c1);
color.add(c2);
color.add(c3);
color.add(c4);
color.add(c5);
fname.add(fn1);
fname.add(fn2);
fname.add(fn3);
fname.add(fn4);
fname.add(fn5);
fstyle.add(fs1);
fstyle.add(fs2);
fstyle.add(fs3);
fstyle.add(fs4);
fstyle.add(fs5);
fsize.add(s1);
fsize.add(s2);
fsize.add(s3);
fsize.add(s4);
fsize.add(s5);
format.add(color);
format.add(fname);
format.add(fstyle);
format.add(fsize);
154
mbr.add(file);
mbr.add(edit);
mbr.add(format);
setMenubar(mbr);
f1.addActionListener(this);
f2.addActionListener(this);
f3.addActionListener(this);
f4.addActionListener(this);
f5.addActionListener(this);
f6.addActionListener(this);
e1.addActionListener(this);
e2.addActionListener(this);
e3.addActionListener(this);
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
fn1.addActionListener(this);
fn2.addActionListener(this);
fn3.addActionListener(this);
fn4.addActionListener(this);
fn5.addActionListener(this);
fs1.addActionListener(this);
fs2.addActionListener(this);
fs3.addActionListener(this);
fs4.addActionListener(this);
s1.addActionListener(this);
s2.addActionListener(this);
s3.addActionListener(this);
s4.addActionListener(this);
s5.addActionListener(this);
f = new Font(“Times New Roman”,Font.PLAIN,20);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionPerformed( );
if(str.equals(“Red”))
setBackground(Color.red);
else if(str.equals(“Green”))
setBackground(Color.green);
else if(str.equals(“Pink”))
setBackground(Color.pink);
else if(str.equals(“Magenta”))
setBackground(Color.magenta);
else if(str.equals(“Times New Roman”))
155
f = new Font(f.getName( ),Font.BOLD,f.getSize( ));
else if(str.equals(“Italic”))
f=new Font(f.getName(),Font.Italic,f.getSize( ));
else if(str.equals(“Bold Italic”))
f=new Font(f.getName( ),Font.BOLD+Font.ITALIC,f.getSize());
else if(str.equals(“24”))
f=new Font(f.getName( ),f.getStyle( ),24);
else if(str.equals(“28”))
f =new Font(f.getName( ),f.getStyle( ),28);
else if(str.equals(“32”))
f =new Font(f.getName( ),f.getStyle( ),32);
else if(str.equals(“36”))
f = new Font(f.getName( ),f.getStyle( ),36);
else if(str.equals(“40”))
f = new Font(f.getName( ),f.getStyle( ),40);
repaint();
}
public void paint(Graphics g)
{
g.setFont(f);
g.drawstring(“Welcome to Java”,100,100);
}
}
class SubMenuDemo
{
public static void main(String args[])
{
MyMenu mf = new MyMenu ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
156
22.3.3 Checkbox MenuItem:
You can create a checkable Menuitem by using the class Checkbox MenuItem.
Syntax:
Here option name is the name shown in the menu. Checkable items operable as
toggle. You can obtain the status of the checkable item by calling getState( ). If the
item is checked, getState( ) returns true. Otherwise it returns false.
Each time a checkbox MenuItem is checked or unchecked an itemevent is generated.
Thus we must implemented the ItemListener interface.
Program:
import java.awt.*;
import java.awt.event.*;
157
fs1 = new CheckboxMenuItem("Bold");
fs2 = new CheckboxMenuItem("Italic");
158
s1.addActionListener(this);
s2.addActionListener(this);
s3.addActionListener(this);
s4.addActionListener(this);
s5.addActionListener(this);
fs1.addItemListener(this);
fs2.addItemListener(this);
f=new Font("Times New Roman",Font.PLAIN,20);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Red"))
setForeground(Color.red);
else if(str.equals("Green"))
setForeground(Color.green);
else if(str.equals("Blue"))
setForeground(Color.blue);
else if(str.equals("Pink"))
setForeground(Color.pink);
else if(str.equals("Magenta"))
setForeground(Color.magenta);
else if(str.equals("24"))
f = new Font(f.getName( ),f.getStyle( ),24);
else if(str.equals("28"))
f= new Font(f.getName( ),f.getStyle( ),28);
else if(str.equals("32"))
f = new Font(f.getName( ),f.getStyle( ),32);
else if(str.equals("36"))
f = new Font(f.getName( ),f.getStyle( ),36);
else if(str.equals("40"))
f = new Font(f.getName( ),f.getStyle( ),40);
repaint( );
}
public void itemStateChanged(ItemEvent ie)
{
if(fs1.getState( )== true && fs2.getState( ) ==false)
f=new Font(f.getName( ),Font.BOLD,f.getSize( ));
else if(fs1.getState( )== false && fs2.getState( )==true)
f=new Font(f.getName( ),Font.ITALIC,f.getSize( ));
else if(fs1.getState( )== true && fs2.getState( )==true)
f=new Font(f.getName( ),Font.BOLD+Font.ITALIC,f.getSize( ));
else
f=new Font(f.getName( ),Font.PLAIN,f.getSize( ));
repaint();
}
public void paint(Graphics g)
159
{
g.setFont(f);
g.drawString("Welcome to Java",100,100);
}
}
class CMenu
{
public static void main(String args[])
{
Myframe mf= new Myframe( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
It works just like Menu but produces a menu that can be displayed at a specific
location. PopupMenu provides a flexible, useful, alternative for some types of menu
situation.
Program:
import java.awt.*;
import java.awt.event.*;
class Popup extends Frame implements ActionListener
{
PopupMenu P1;
Popup( )
{
super(“Popup Menu”);
P1= new PopupMenu( );
MenuItem c1 = new MenuItem(“Red”);
MenuItem c2 = new MenuItem(“Blue”);
MenuItem c3 = new MenuItem(“Green”);
MenuItem d = new MenuItem("-");
MenuItem c4 = new MenuItem(“Pink”);
MenuItem c5 = new MenuItem(“Magenta”);
P1.add(c1);
P1.add(c2);
P1.add(c3);
P1.add(d);
P1.add(c4);
P1.add(c5);
add(P1);
c1.addActionListener(this);
c2.addActionListener(this);
160
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
addMouseListener(new Mouse());
}
class Mouse extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
P1.show(me.getComponent(),me.getX(),me.getY( ));
}
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals(“Red”))
setBackground(Color.red);
else if(str.equals(“Blue”))
setBackground(Color.blue);
else if(str.equals(“Green”))
setBackground(Color.green);
else if(str.equals(“Pink”))
setBackground(Color.pink);
else
setBackground(Color.magenta);
}
}
class PopMenuDemo
{
public static void main(String args[])
{
Popup mf= new Popup( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
22.4 Dialogs:
Dialog box, like frame, is pop-up llwindow on which user inteface components can be
laid out. Usally they are used to display message and get specific information from
the user. Though a dialog resembles and behaves like a frame, ther are some major
differences between the two. They are:
▪ Unlike frames, a dialog has parent (0r a owner) window. The dialog is
automatically closed when the parent window is closed.
161
▪ A dialog box can be made modal. A modal dialog prevents user input to other
windows in the application until dialog is closed.
162
Constructors Description
Dialog(Frame, boolean) Create a new dialog, which is initially invisible.
The frame acts as the parent of the dialog. The
dialog is closed when its parent is closed. The
Boolean value specifies whether the dialog is
modal or not
Dialog(Frame, String, boolean) Creates a new dialog with the specified string
as the title. The other two parameters are the
same as in the previous constructor.
File Dialog provides a platform-specific dialog that lets us to choose a file and to save
or open it.
Constructors Description
FileDialog(Frame, String) Creates an Open File Dialog that lets the user
select a file name from a file listing
The Frame acts as the parent (owner) of the
dialog. The String is the title of the file dialog.
FileDialog(Frame, String, int) This constructor behaves exactly the same way as
the pervious one, except that the int parameter is
used to determine whether the dialog is for
loading or saving a file. The two options are
FileDialog.LOAD and FileDialog.SAVE.
Note: the file dialog does not actually load or save files. It is used only to select a
file from the file listing. The file dialog is modal dialog.
Methods Description
GetDirectory() Returns the directory of the file selected as a String
GetFile() Returns the name of the file selected as as String. This
method returns a null string if the user dismisses the
dialog without selecing a file.
Program:
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.*;
public class Editor extends Frame
{
String filename;
TextArea tx ;
Clipboard clip=getToolkit().getSystemClipboard();
163
Editor()
{
setLayout(new GridLayout(1,1));
tx=new TextArea();
add(tx);
setTitle("untitled");
MenuBar mb=new MenuBar();
Menu F=new Menu("File");
MenuItem n=new MenuItem("New");
MenuItem o=new MenuItem("Open");
MenuItem s=new MenuItem("Save");
MenuItem e=new MenuItem("Exit");
n.addActionListener(new New());
F.add(n);
o.addActionListener(new Open());
F.add(o);
s.addActionListener(new Save());
F.add(s);
e.addActionListener(new Exit());
F.add(e);
mb.add(F);
Menu E=new Menu("Edit");
MenuItem cut=new MenuItem("Cut");
MenuItem copy=new MenuItem("Copy");
MenuItem paste=new MenuItem("Paste");
cut.addActionListener(new Cut());
E.add(cut);
copy.addActionListener(new Copy());
E.add(copy);
paste.addActionListener(new Paste());
E.add(paste);
mb.add(E);
setMenuBar(mb);
164
if(fd.getFile()!=null)
{
filename=fd.getDirectory()+fd.getFile();
setTitle(filename);
ReadFile();
}
tx.requestFocus();
}
}
class Save implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
FileDialog fd=new FileDialog(Editor.this,"Save
File",FileDialog.SAVE);
fd.show();
if(fd.getFile()!=null)
{
filename=fd.getDirectory()+fd.getFile();
setTitle(filename);
try
{
DataOutputStream d=new DataOutputStream(new
FileOutputStream(filename));
String line=tx.getText();
BufferedReader br=new BufferedReader(new
StringReader(line));
while((line=br.readLine())!=null)
{
d.writeBytes(line+"\r\n");
}
d.close();
}
catch(Exception ex)
{
System.out.println("File not found");
}
tx.requestFocus();
}
}
}
class Exit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
void ReadFile()
{
BufferedReader d;
StringBuffer sb=new StringBuffer();
try
{
d=new BufferedReader(new FileReader(filename));
String line;
while((line=d.readLine())!=null)
sb.append(line+"\n");
tx.setText(sb.toString());
d.close();
165
}
catch(FileNotFoundException fe)
{
System.out.println("File not found");
}
catch(IOException ioe)
{
}
}
class Cut implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sel=tx.getSelectedText();
StringSelection ss=new StringSelection(sel);
clip.setContents(ss,ss);
tx.replaceRange("
",tx.getSelectionStart(),tx.getSelectionEnd());
}
}
class Copy implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sel=tx.getSelectedText();
StringSelection clipString=new StringSelection(sel);
clip.setContents(clipString,clipString);
}
}
class Paste implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Transferable cliptran=clip.getContents(Editor.this);
try
{
String sel=(String)
cliptran.getTransferData(DataFlavor.stringFlavor);
tx.replaceRange(sel,tx.getSelectionStart(),tx.getSelec
tionEnd());
}
catch(Exception exc)
{
System.out.println("Not String flavor");
}
}
}
public static void main(String args[])
{
Frame f=new Editor();
f.setSize(500,400);
f.setVisible(true);
f.show();
}
}
166
23. JFC - Java Foundation Classes
23.1 Introduction to JFC
The earlier version of java were released with some simple libraries. JDK1.2 was
introduced with a new set of packages, the Java Foundation Classes, or JFC that
includes an improved user interface called the Swing Components.
23.2 Swings:
Swing Components conatin a pluggable look and feel (PL&F). This allows all
applications to run with the native look and feel on different platforms. PL&F
allows applications to have the same behavior on various platforms(os). JFC contains
operating system neutral look and feel.
JComponent
JToggle JMenu
Button Bar
JRadio JCheck
Button Box JCheckBox JMenu JRadioButton
Menu Item MenuItem
Windows
Applet
JApplet
JDialog JFrame
167
23.3.1 JOptionPane:
Dialog boxes are windows that typically are used to display important messages to
the user of an application. Java2 already includes class dialog containing
information.
JOptionPane.showInputDialog(String str);
The argument showInputDialog indicates to the user what to do in the textfield . The
message is called a prompt because it directs the user to take a specific action. The
user types characters in the text field, then clicks on button to written the string to
the program.
Note: If the user clicks the cancel button, a run time logical error will occur.
Here the first argument will be the keyword null. The second argument is the string
to display. The third argument is the string to display title bar at the dialog. The
fourth argument is the value indicating the type of message dialog to display.
SUM
i
Ok 1 ?
Program:
import javax.swing.*;
class Jop
{
public static void main (String args[])
{
String str;
int a,b,c;
168
try
{
str = JOptionPane.showInputDialog("Enter the 1st no: ");
a = Integer.parseInt(str);
str = JOptionPane.showInputDialog("Enter the 2nd no: ");
b = Integer.parseInt(str);
c = a+b;
JOptionPane.showMessageDialog(null,"SUM " +c, "Result Box",
JOptionPane. INFORMATION_MESSAGE);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Format Error", "Error Window",
JOptionPane. ERROR_MESSAGE);
}
}
}
23.3.2 JFrame :
Unlike a Frame, a JFrame has some notion of how to respond when the user
attempts to close the window. The default behavior is to simply hide the JFrame
when the user closes the window. To change the default behavior, you invoke the
method setDefaultCloseOperation(int). To make the JFrame behave the same as
a Frame instance, use
Program:
import javax.swing.*;
import java.awt.*;
class Myframe extends JFrame
{
Myframe()
{
super(“Frame Window”);
}
public void paint(Graphics g)
{
setBackground(Color.pink);
g.drawString(“Welcome to java”,100,100);
g.drawOval(100,100,50,50);
}
}
class JFrameDemo
{
public static void main(String args[])
{
Myframe mf = new Myframe( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
169
23.3.3 JPanel:
Syntax
JPanel panelobj = new JPanel( );
Syntax :
getContentPane.add(panelobj);
23.3.4 JLabel:
Syntax
JLabel obj = new JLabel (String str);
Program:
import java.awt.*;
import javax.swing.*;
class Mypanel extends JFrame
{
Mypanel ( )
{
super(“Label Demo”);
JPanel jp = new JPanel( );
Font f= new Font("Verdana",Font.BOLD,20");
JLabel L1= new JLabel(“Welcome to JFC Swing“);
L1.setFont(f);
jp.add(L1);
getContentPane().add(jp);
}
}
class JLableDemo
{
public static void main (String args[])
{
Mypanel mf = new Mypanel ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
23.3.5 JButton:
Note:
A Shortcut Key is the underlined character you find in buttons. You can select a
button by pressing a combination of the alt key a character. You can set the
shortcut key using setMnemonic method.
170
23.3.5.2 Adding Tool Tips:
Tool tips are short informative messages that you see when you reset the
mousecursor on a button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyButton extends JFrame implements ActionListener
{
JPanel jp;
MyButton( )
{
super("ShortCut Frame");
jp = new JPanel( );
JButton b1 = new JButton("red");
JButton b2 = new JButton("green");
JButton b3 = new JButton("blue");
JButton b4 = new JButton("pink");
JButton b5 = new JButton("magenta");
b1.setMnemonic('r');
b2.setMnemonic('g');
b3.setMnemonic('b');
b4.setMnemonic('p');
b5.setMnemonic('m');
b1.setToolTipText("set red background color");
b2.setToolTipText("set green background color");
b3.setToolTipText("set blue background color");
b4.setToolTipText("set pink background color");
b5.setToolTipText("set magenta background color");
jp.add(b1);
jp.add(b2);
jp.add(b3);
jp.add(b4);
jp.add(b5);
getContentPane( ).add(jp);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals("red"))
jp.setBackground(Color.red);
else if(str.equals("green"))
jp.setBackground(Color.green);
else if(str.equals("blue"))
jp.setBackground(Color.blue);
else if(str.equals("pink"))
jp.setBackground(Color.pink);
else
jp.setBackground(Color.magenta);
}
public static void main(String arg[])
{
171
MyButton mb = new MyButton();
mb.setSize(400,150);
mb.setVisible(true);
mb.setLocation(200,200);
}
}
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyImage extends JFrame
{
MyImage ( )
{
super(“ImageButton”);
JPanel jp = new JPanel( );
JButton b1 = new JButton(“Image”);
The Jcomponent class contains a Border property. This refer a class that implements
the Border interface. Painting of the border is handled by the component when a
border is specified for the component. When a border has been set for a Jcomponent
instance, the size of the border is used as the insets property for that component.
Program:
import java.awt.*;
import javax.swing.border.*;
import javax.swing.*;
172
JLabel l1 = new JLabel("World Computers");
JLabel l2 = new JLabel("World Computers");
JLabel l3 = new JLabel("World Computers");
JLabel l4 = new JLabel("World Computers");
l1.setFont(f);
Border line1 = BorderFactory.createMatteBorder(0,0,5,5,Color.gray);
Border line2 = BorderFactory.createBevelBorder(BevelBorder.RAISED);
Border line3=
BorderFactory.createEtchedBorder(Color.red,Color.yellow);
Border line4 = BorderFactory.createLineBorder(Color.pink,5);
l1.setBorder(line1);
l2.setBorder(line2);
l3.setBorder(line3);
l4.setBorder(line4);
jp.add(l1);
jp.add(l2);
jp.add(l3);
jp.add(l4);
getContentPane().add(jp);
getContentPane().add(jp);
}
}
class BorderDemo1
{
public static void main(String args[])
{
Mybrd mf = new Mybrd( );
mf.setSize( 300,300);
mf.setVisible(true);
}
}
The new Java 2D api provided advanced two dimentsional graphics, capabilities for
programmers who required detailed and complex graphical manipulations. Drawing
with the Java 2D api is accomplished with an instance of Graphics 2D.
GradientPaint(float x1, float y1, Color color1, float x2, float y2,
Color color2)
Constructs a simple acyclic GradientPaint object.
GradientPaint(float x1, float y1, Color color1, float x2, float y2,
Color color2, boolean cyclic)
Constructs either a cyclic or acyclic GradientPaint object depending on the boolean
parameter
173
Program:
23.6 JColorChooser:
One of the newer feature of Java is the predefined GUI Component JColorChooser
for selecting colours.
Syntax :
JChooseColor.showDialog(this,String title,default Color);
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyColor extends JFrame implements ActionListener
{
JPanel jp;
Jbutton b1;
MyColor ()
{
super(“Color Chooser”);
b1 = new JButton(“Color”);
jp.add(b1);
b1.addActionListener(this);
getContentPane( ).add(jp);
}
}
public void actionPerformed(ActionEvent ae)
{
Color c;
c= JColorChooser.showDialog(this,”Color Box”,Color.red);
jp.setBackground(c);
}
}
class JColorChooserDemo
{
public static void main(String args[])
{
MyColor me = new MyColor ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
174
23.7 JTextField:
Program:
import java.awt.*;
import java.awt.event.*;
import javax.awt.swing.*;
import javax.awt.swing.event.*;
class MyText extends JFrame implements ActionListener
{
JTextField t1,t2,t3;
MyText ( )
{
super(“Text Demo”);
JPanel jp = new JPanel( );
JLabel l1 = new JLabel (“Enter the 1st no :”);
JLabel l2 = new JLabel (“Enter the 2nd no:”);
JLabel l3 = new JLabel (“Result :”);
t1 = new JTextField(5);
t2 = new JTextField(5);
t3 = new JTextField(5);
JButton b1 =new JButton(“SUM”);
jp.add(l1);
jp.add(t1);
jp.add(l2);
jp.add(t2);
jp.add(t3);
jp.add(l3);
jp.add(t3);
jp.add(b1);
b1.addActionListener(this);
getContentPane( ).add(jp);//add panel to the JFrame
}
public void actionPerformed(ActionEvent ae)
{
String str;
int n1,n2,n3;
str = t1.getText( );
n1 = Integer.parseInt(str);
str = t2.getText( );
n2 = Integer.parseInt(str);
n3 = n1+n2;
t3.setText(n3+ “ “);
}
}
class JTextFieldDemo
public static void main(String args[])
{
MyText mf = new MyText( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
175
23.8 JPasswordField:
JPasswordField is a single line text field in which text can be entered by the user
from the keyboard or text can simply be displayed *.
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
if(str.equals("Ok"))
{
String uname=t1.getText();
uname=uname.trim();
String pass=t2.getText();
if(uname.equals("World") && pass.equals("admin"))
{
176
}
}
}
catch(Exception e)
{
System.out.println("Error in user "+e);
}
if(str.equals("Close"))
{
System.exit(0);
dispose();
}
}
}
class Jpass
{
public static void main(String args[])
{
Mypass mf = new Mypass( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
23.8 JCheckBox:
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Myframe extends JFrame implements ItemListener
{
JTextField t1;
JCheckBox c1,c2;
Myframe()
{
super(“Dialog Box”);
JPanel jp = new JPanel();
t1 = new JtextField(15);
c1 = new JCheckBox(“BOLD”);
c2 = new JCheckBox(“ITALIC”);
jp.add(t1);
jp.add(c1);
jp.add(c2);
c1.addItemListener(this);
c2.addItemListener(this);
getContentPane().add(jp);
}
public void itemStateChanged(ItemEvent ie)
{
Font f;
if(c1.isSelected( ) == true && c2.isSelected ( ) == true)
177
else if(c1.isSelected ( ) == false && c2 .isSelected() ==
true )
23.9 JRadioButton:
JRadioButton are used for single selection among the group of buttons. Frist Create
ButtonGroup and then create a JRadioButton and add Each RadioButton to the
BorderGroup
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MyRadio extends JFrame implements ItemListener
{
JRadioButton c1,c2,c3,c4,c5,c6;
JPanel jp;
MyRadio ( )
{
super(“Dialog Box”);
jp = new JPanel( );
ButtonGroup col = new ButtonGroup( );
c1 = new JRadioButton(“Red”);
c2 = new JRadioButton(“Green”);
c3 = new JRadioButton(“Blue”);
c4 = new JRadioButton(“Pink”);
c5 = new JRadioButton(“Magenta”);
c6 = new JRadioButton(“Black”);
col.add(c1);
col.add(c2);
col.add(c3);
col.add(c4);
col.add(c5);
col.add(c6);
jp.add(c1);
jp.add(c2);
jp.add(c3);
jp.add(c4);
jp.add(c5);
jp.add(c6);
c1.addItemListener(this);
178
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
c6.addItemListener(this);
getContentPane( ).add(jp);
}
public void itemStateChanged(ItemEvent ie)
{
if(ie.getSource ( ) == c1)
jp.setBackground(Color.red);
else if(ie.getSource( ) == c2)
jp.setBackground(Color.green);
else if(ie.getSource( ) == c3)
jp.setBackground(Color.blue);
else if(ie.getSource( ) == c4)
jp.setBackground( Color.pink);
else
jp.setBackground(Color.black);
}
}
class JRadioDemo
{
public void main(String args[])
{
MyRadio mf = new MyRadio ( );
mf.setSize( );
mf.setVisible(true);
}
}
23.10 JCombobox:
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Mycombo extends JFrame implements ItemListener
{
JPanel jp;
JCombobox col;
Mycombo
{
super (“Jcombo Demo”);
jp = new JPanel ( );
col = new JCombobox();
col.addItem(“Red”);
col.addItem(“Green”);
col.addItem(“Blue”);
col.addItem(“Pink”);
col.addItem(“Magenta”);
col.addItem(“Yellow”);
jp.add(col);
col.addItemListener(this);
getContentPane( ).add(jp);
}
public void ItemStateChanged (ItemEvent ie)
{
int n = col.getSelectedIndex( );
179
if(n == 0)
jp.setBackground(Color.red);
else if(n == 1)
jp.setBackground(Color.green);
else if(n == 2)
jp.setBackground(Color.blue);
else if(n == 3)
jp.setBackground(Color. Yellow);
}
}
class JComboboxDemo
{
public static void main(String args[ ])
{
Mycombo mf = new Mycombo ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
23.11 JList:
A JList is functionally similar to JComboBox menu in that it allows the user to select
one or more object from the list of choices. A Jlist will generate event when it
selection changes, or when any of its items change. The difference between a JList
and a Jcombox menu are given below.
Unlike Jcombox, which display only the single-selected item, the list can be made to
show any number of choices in the visible window.
Program:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
class MyList extends JFrame implements ListSelectionListener
{
JPanel jp;
JList col;
MyList( )
{
super("List Demo");
jp = new JPanel( );
String str[ ] =
{"Red","Green","Blue","Pink","Magenta","Yellow"};
col = new JList(str);
180
Border line2 =
BorderFactory.createBevelBorder(BevelBorder.RAISED);
col.setBorder(line2);
jp.add(col);
getContentPane( ).add(jp);
col.addListSelectionListener(this);
}
23.12 JSlider:
JSlider enables the user to select from a range of integer values. JSlider has a thick
marks and the thumb that allows the user to select a value. Jsliders have either a
horizontal orientation or a vertical orientation.
SwingConstants.HORIZONTAL or SwingConstants.VERTICAL
The second and third argument indicate the minimum and maximum integer values
in the range of values for this Jsliders. The last argument indicates the initial value
of the JSlider. JSliders generate ChangeEvent when a user interacts with the JSlider.
To accesss this event, we have to use ChangeListener(interface) has a method
StateChanged( ) to access the JSlider. Method getValue( ) returns the current
thumb position.
181
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class MySlider extends JFrame implements ChangeListener
{
JPanel jp;
JSlider s1,s2,s3;
MySlider ( )
{
super(“Slider Demo”);
jp = new JPanel( );
s1 = new JSlider(SwingConstants.HORIZONTAL,0,255,0);
s2 = new JSlider(SwingConstants.HORIZONTAL,0,255,0);
s3 = new JSlider(SwingConstants.HORIZONTAL,0,255,0);
jp.add(s1);
jp.add(s2);
jp.add(s3);
s1.addChangeListener(this);
s2.addChangeListener(this);
s3.addChangeListener(this);
getContentPane().add(jp);
}
public void stateChanged(ChangeEvent ce)
{
Color c = new Color(s1.getValue( ),s2.getValue( ),
s3.getValue( ));
jp.setBackground(c);
}
}
class JSliderDemo
{
public static void main(String args[])
{
MySlider mf = new MySlider ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
23.13 JPopMenu
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyPopup extends JFrame implements
ActionListener
{
JPanel jp;
JPopupMenu col;
182
MyPopup ( )
{
super("PopMenu");
jp = new JPanel( );
col = new JPopupMenu( );
JMenuItem c1 = new JMenuItem("Red");
JMenuItem c2 = new JMenuItem("Green");
JMenuItem c3 = new JMenuItem("Blue");
JMenuItem c4 = new JMenuItem("Pink");
JMenuItem c5 = new JMenuItem("Magenta");
col.add(c1);
col.add(c2);
col.add(c3);
col.addSeparator();
col.add(c4);
col.add(c5);
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
addMouseListener(new press());
addWindowListener(new W());
getContentPane( ).add(jp);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals ("Red"))
jp.setBackground(Color.red);
else if(str.equals("Green"))
jp.setBackground(Color.green);
else if(str.equals("Blue"))
jp.setBackground(Color.blue);
else if(str.equals("Pink"))
jp.setBackground(Color.pink);
else
jp.setBackground(Color.magenta);
}
class press extends MouseAdapter
{
class Jpop
{
public static void main(String args[])
{
183
MyPopup mf = new MyPopup ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
23.14 JMenuBar :
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
184
edit.add(e1);
edit.add(e2);
edit.add(e3);
color.add(c1);
color.add(c2);
color.add(c3);
color.add(c4);
color.add(c5);
mbr.add(file);
mbr.add(edit);
mbr.add(color);
setJMenuBar(mbr);
c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);
c4.addActionListener(this);
c5.addActionListener(this);
getContentPane().add(jp);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand( );
if(str.equals("Red"))
jp.setBackground(Color.red);
else if(str.equals("Green"))
jp.setBackground(Color.green);
else if(str.equals("Blue"))
jp.setBackground(Color.blue);
else if(str.equals("Pink"))
jp.setBackground(Color.pink);
else
jp.setBackground(Color.magenta);
}
}
class JMenuDemo
{
public static void main(String args[])
{
MyMenu mf = new MyMenu ( );
mf.setSize(300,300);
mf.setVisible(true);
}
}
185