Core Java New
Core Java New
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.
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....
Simple and Powerful
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.
Distributed
4
Java is designed for the distributed environment of the Internet, because it
handles TCP/IP protocols. This allowed objects on two different computers to execute
procedures(programs) remotely.
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 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 [Link] [Link]
2. Java Programming and Fundamentals
2.1 Structure of a JAVA program:
class <Class_name>
{
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.
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: [Link]
6. To run a java program, executes the interpreter specifying the name of the
class file on the command line.
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)
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.
//real Numbers
if([Link](aChar))
{
[Link]("The Character "+aChar +" is upper
case.");
}
else
{
[Link]("The Character "+aChar +" is lower
case.");
}
[Link]("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:
[Link]
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.
class Argument
{
public static void main(String args[])
{
int a,b,c;
float f;
a=[Link](args[0]);
b=[Link](args[1]);
c=[Link](args[1]);
f=(float)((a+b)/c);//type cast to float
[Link](“Result =”+f);
}
}
To run this above program after complied
C:\>java Argument 5 2 2
OUTPUT : 3.5
a=[Link](args[0]);
b=[Link](args[1]);
import [Link].*;
class Scan
{
public static void main(String arg[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter a number");
int i = [Link]();
[Link]("Enter a number");
int j=[Link]();
int k=i+j;
[Link](k);
}
}
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;
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
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;
[Link](x&y);
[Link](x|y);
[Link](x^y);
[Link](x>>2);
[Link](x<<2);
}
}
OUTPUT :
1
7
6
1
20
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,big=0;
a=[Link](args[0]);
b=[Link](args[1]);
if(a>b)
{
big=a;
}
if(b>a)
{
big=b;
}
[Link](“Big= "+big);
}
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;
}
[Link](“Big= "+big);
OUTPUT :
100
20
Big=100
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;
}
[Link](“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;
[Link]("Percentage = "+per);
if(per>=75)
{
[Link]("Distinction");
}
else if(per>=60)
{
[Link]("First Class");
}
else if(per>=50)
{
[Link]("Second Class");
}
else if(per>=40)
{
[Link]("Third Class");
}
else
{
[Link]("No Grade");
}
}
}
OUTPUT
Total Marks = 301
Percentage = 60.2
First Class
Syntax:
switch(expression)
{
case constant1:
statement1
break;
case constant2:
statement2
break;
-------------
-------------
case constant n:
statement n
break;
default:
default statement
break;
}
class SwitchDemo
{
public static void main(String arg[])
{
int n = [Link](arg[0]);
switch(n)
{
case 1:
[Link]("The number is one");
break;
case 2:
[Link] ("The number is two");
break;
case 3:
[Link] ("The number is three");
break;
default:
[Link] ("The number is not
between 1 and 3");
break;
}
[Link] ("\nEnd of program");
}
}
OUTPUT
C:\> java SwitchDemo 2
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=[Link](arg[0]);
int i=1,s=0;
while(i<=n)
{
s=s+i;
i++;
}
[Link]("Sum of n Number is “+s);
}
}
OUTPUT :
10
55
}while(condition);
Program:
class DoWhileDemo
{
public static void main(String arg[])
{
int n=[Link](arg[0]);
int i=1,f=0;
do
{
f=f*i;
i++;
} while(i<=n);
[Link]("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.
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=[Link](arg[0]);
int s=0;
if(n==0)
[Link](s);
else
for(int i= 1;i<=n;i++)
{
s=s+i;
}
[Link]("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.
Continue is similar to break, except that instead of halting the execution of the
loop, it starts the next iteration. The following example demonstrates the usage of
continue statement.
for(int i=2;i<n;i++)
{
if(n%i==0)
break;
else
continue;
}
if(i==n)
[Link]("Given number is prime");
else
[Link] ("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: {
[Link]("Before the break");
if(t)
{
break b;
}
[Link]("This will not execute");
}
[Link]("This will not execute");
}
[Link]("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++)
{
[Link](i+" ");
if(i % 2 == 0)
{
continue;
}
[Link]();
}
}
}
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=[Link](arg[0]);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
[Link](j+" ");
}
[Link]();
}
}
}
OUTPUT:
Java Nest 5
1
1 2
1 2 3
1 2 3 4
1 2 3 3 4 5
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 [Link].*;
class SingleArray
{
public static void main(String arg[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter array size ");
int size=[Link]();
Program:
import [Link].*;
class Array
{
public static void main (String arg []) throws IOException
{
Scanner sc = new Scanner([Link]);
[Link]("Enter array size ");
int size=[Link]();
You have already come across several such methods in earlier chapters. Some
examples are [Link](), readLine(), [Link]();
Type 1:
class Method1
{
public static int sum(int a, int b)
{
int c;
c=a+b;
return(c);
}
public static void main(String args[])
{
int k;
Scanner sc = new Scanner([Link]);
[Link]("Enter array size ");
int x= [Link]();
int y= [Link]();
k=sum(x,y);
[Link](k);
int z=sum(k,x);
[Link](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();
[Link]("Biggest of two nos = "+big)
}
}
Type 3:
class Method3
{
static void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
[Link]("X = "+ x +"Y = "+ y);
}
public static void main(String args[])
{
int a=10, b=20;
swap(a,b) //calling of swap function
[Link]("End of main function");
}
}
Type 4:
class Method4
{
static void swap()
{
int a=10, b=10,t;
t=a;
a=b;
b=t;
[Link]("A = "+ a +"B = "+ b);
}
public static void main(String args[])
{
swap() //calling of swap function
[Link]("End of main function");
}
}
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.
MethodClass
Overloading
MethodData
Overridding
Class Arith
Data1
Data
7.2 Class
Data2 int a
A class is a prototype that defines the Data and Code common to all objects
of a particular kind. Data3 int b
A class defines the structure and behaviour of the objects. The elements of a
class are calledMethods
members. Code and data are two importantint c elements of a class.
The code that actsMethod1()
on the data is called method. The data defined by the calss is
called variables. Methods
sum()
Method2()
Method3() sub()
mul()
Class grouping data and Methods
7.2.1 Class Declaration.
Syntax:
Syntax:
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>
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
7.4 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;
[Link](t.c);
}
}
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=[Link](p.a,p.b);
[Link](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;
[Link](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.
Program :
class Item
{
private int a,b,c;
public void sum( )
{
a=20;b=10;
c=a+b;
[Link] ( c );
}
}
class PrivateAccess
{
public static void main(String args[])
{
Item t=new Item( );
[Link]( );
}
}
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);
[Link](z);
}
}
class PrivateAccess1
{
public static void main (String args[])
{
Item t=new Item( );
[Link](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.
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;
[Link](t.a);
[Link](t1.a);
}
}
Syntax:
class UseStatic
{
static int a=3;
static int b;
static void meth(int x)
{
[Link] (“ X = “ + x);
[Link] (“ a = “ + a);
[Link] (“ b = “ + b);
}
static //static block
{
[Link] (“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.
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();
[Link]([Link](20.4,30));
[Link]([Link](10,20));
[Link]([Link](10,20,30));
}
}
7.8 Constructor:
A Constructor is a special kind method that determines how an object is
initialized when created.
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;
[Link]( 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;
[Link]( c );
}
}
class ConstParaDemo
{
public static void main(String args[])
{
ConstPara p=new ConstPara(30,10);
}
}
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);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
Program :
Test(int i, int j)
{
a = i;
b = j;
}
boolean equals(Test o)
{
[Link]("o.a = "+ o.a + "a = " + a);
[Link]("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);
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 = [Link]();
[Link]("ob1.a: " + ob1.a);
[Link]("ob2.a: " + ob2.a);
ob2 = [Link]();
[Link]("ob2.a after second increase: "
+ ob2.a);
}
}
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();
[Link]([Link](20,10));
[Link]([Link](20,10));
}
}
using object of derived (sub(class)) we can access all the properties of super class.
8.2 Multilevel Inheritance :
It is a process of creating a sub class from another subclass.
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();
[Link]([Link](20,10));
[Link]([Link](20,10));
[Link]([Link](20,10));
[Link]([Link](20,10));
}
}
class A
{
A()
{
[Link]("A is called ");
}
}
class B extends A
{
B()
{
[Link]("B is called ");
}
}
class C extends B
{
C()
{
[Link]("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: [Link]
[Link]();
class main
{
int i=12;
}
class sub extends main
{
int i=17;
void display()
{
[Link]("I = "+i);
[Link]("Super.i = "+super.i);
}
}
class Super
{
public static void main(String arg[])
{
sub s = new sub()
[Link]();
}
}
Example 2:
class Super
{
int i;
}
class sub extends Super
{
int i;
sub(int x, int y)
{
i=x;
super.i=y;
}
void display()
{
[Link]("I in subclass = "+i);
[Link]("I in superclass = "+super.i);
}
}
class CallSuper
{
public static void main(String arg[])
{
sub s = new sub(10,20);
[Link]();
}
}
}
void display()
{
[Link]("I = "+i+"\nJ = "+j);
[Link]("K = "+k);
}
}
class CallSuper
{
public static void main(String arg[])
{
sub s = new sub(10,20,30);
[Link]();
}
}
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();
[Link]([Link](20,10));
p1=new C();
[Link]([Link](20,10));
p1=new D();
[Link]([Link](20,10));
p1=new A();
[Link]([Link](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;
p=new B();
[Link]([Link](10,20));
p=new C();
[Link]([Link](10,20));
p=new D();
[Link]([Link](10,2));
}
}
OUTPUT:
10
200
2
class FinalVar
{
public static void main(String args[])
{
final int a=10;
a=a+5;//error
[Link](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);
}
}
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();
[Link]([Link](10,20));
p=new C();
[Link]([Link](10,20));
p=new D();
[Link]([Link](10,2));
[Link]([Link](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);
}
}
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;
[Link](c);
}
}
class ThisDemo
{
public static void main(String args[])
{
A P1= new A ( ) ;
A P2= new A ( );
[Link]( );
[Link]( );
[Link]( );
}
}
OUTPUT :
70
30
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();
[Link]([Link](20,10));
}
}
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);
}
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);
}
}
class InterfaceDemo3
{
public static void main(String args[])
{
D P=new D( );
[Link]([Link](20,10));
[Link]([Link](20,10));
[Link]([Link](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();
[Link]([Link](P.a,P.b));
}
}
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;
[Link](a);
[Link]("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.
In the example, we haven't supplied any exception handlers of our own, so the
exception is caught by the default handler by the java-runtime system.
Any exception that is caught by your program will ultimately processed by the
default handler. Hence default handler display a string describig the exception,
[Link] : / 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=[Link](args[0]);
b=[Link](args[1]);
c=a/b;
[Link]( c );
}
catch(ArithmeticException e)
{
OUTPUT :
C:\> Java ArithException 100 0
Zero divide error.
Program:
import [Link].*;
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;
[Link](a[0]);
[Link](a[1]);
[Link](a[2]);
[Link](a[3]);
[Link](a[4]);
[Link](a[5]);
}
catch(ArrayIndexOutOfBoundException e)
{
[Link](“You cannot access the value of
a[5]” + e);
}
}
}
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;
[Link](a[0]);
[Link](a[1]);
[Link](a[2]);
[Link](a[3]);
[Link](a[4]);
}
catch(NegativeArraySizeException e)
{
[Link](“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=[Link](args[0]);
b=[Link](args[1]);
c=a/b;
[Link](c);
}
catch(NumberFormatException e)
{
[Link](“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=[Link](args[0]);
int b=[Link](args[1]);
int c=a/b;
[Link]("Result = "+c);
}
catch(ArithmeticException e)
{
[Link]("Zero divide error");
f=1;
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Enter minimum two
arguements");
f=1;
}
catch(NumberFormatException e)
{
[Link]("Cannot convert string to
integer");
f=1;
}
if(f==0)
[Link]("Your Transcation is
completed ");
else
[Link]("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)
{
[Link](“Error”);
}
}
10.5 Throw:
It is possible to throw an exception explicitly using throw statement.
Syntax:
class ThrowDemo
{
public static void main(String args[])
{
try
{
int a,b,c;
a=[Link](args[0]);
b=[Link](args[1]);
if(b==0)
throw new ArithmeticException();
else
{
c=a/b;
[Link]( c );
}
}
catch(ArithmeticException e)
{
[Link](“zero divide error”);
[Link]("Result ="+c);
}
}
10.6 Throws:
Syntax:
class WithoutThrows
{
public static void div(int a,int b)
{
int c;
c=a/b;
[Link]( 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;
[Link]("sum ="+c );
}
public static void main(String args[])
{
try
{
div(20,0);
}
catch(ArithmeticException e)
{
[Link]("Error "+e);
}
}
}
10.7 Finally:
When an exception is generated in program, control will be goto catch block
and it will stop the process sometimes it may be necessary to the program to stop
certain activities before termination. Finally creates a block of code that will be
executed after a try or catch block has completed.
class FinallyDemo
{
public static void main(String args[])
{
int a=0,b=0,c=0;
try
{
a=[Link](args[0]);
b=[Link](args[1]);
c=a/b;
}
catch(ArithmeticException e)
{
c=0;
[Link](“Error”+e);
}
finally
{
[Link]( c );
}
}
Program:
import [Link].*;
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. [Link]:
The [Link] package is one of the most important packages in Java. It provides
a no. of classes and interfaces that are fundamental to java programming.
Cloneable
Comparable
Runnable
1. parseByte(String str):-
Program :
class IntegerClass
{
public static void main(String args[])
{
int a,b,c;
a=[Link](args[0]);
b=[Link](args[1]);
c=a+b;
[Link]( c );
}
}
OUTPUT:
10
20
30
b. toBinaryString(int num):
Program:
class BinrayDemo
{
public static void main(String args[])
{
int num;
num = [Link](args[0]);
[Link]([Link](num));
}
}
10111
c. toHexString(int num):
[Link]([Link](num));
OUTPUT: 30
1e
[Link]([Link](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=[Link](args[0]);
b=[Link](args[1]);
c=a+b;
[Link]( c );
}
}
OUTPUT :
16.3
30.5
11.3.5 The Double class:
double=[Link](String s);
[Link]
[Link]
public final class Math extends Object
a) Sqrt( ) :
class SqrtDemo
{
public static void main(String args[])
{
double a,b;
a=[Link](args[0]);
b=[Link](a);
[Link](b);
}
}
OUTPUT:
64
8.0
b) abs():
OUTPUT
-23
23
c) ceil():
OUTPUT
23.123
24
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=[Link](String args[0])
b=[Link](String args[1])
c=[Link](a,b);
[Link]( 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.
Program:
class SinDemo
{
public static void main(String args[])
{
double a,b;
a=[Link](args[0]);
a=a*3.14/180;
b=[Link](a);
[Link](b);
}
}
Degree to Radian:
Radian to degree 180/
/180
b=[Link](a);
b=b*/180
toRadians( ):
class RadianDemo
{
public static void main(String args[])
{
double a,b
a=[Link](args[0]);
a=[Link](a);
b=[Link](a);
[Link](n);
}
}
toDegrees( ):
Program:
class DigitDemo
{
public static void main(String args[])
{
char ch=’a’;
[Link]([Link](ch));
}
}
OUTPUT: false
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("Palar computers");
//or
String str1=”palar computer centre”;
[Link](str);
[Link](str1);
}
}
class StringLength
{
public static void main(String args[])
{
String str = ”palar computer centre”;
[Link]([Link]( ));
}
}
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= ”Palar Computer Centre”;
[Link] ([Link](‘o’));
}
OUPUT: 7.
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=”Palar Computer Centre”;
[Link]([Link](“put”));
}
OUPUT: 9
{
String str = “palar computer centre “
[Link]([Link](3));
}
OUTPUT : a
12.7 equals():
class EqualDemo
{
public static void main(String args[])
{
String str1=”palar computer”;
String str2=”palar computer”;
[Link]([Link](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
class Startwith
{
public static void main(String args[])
{
String str = “palar computer”;
[Link]([Link](“palar”));
}
}
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=”palar computer”;
[Link]([Link](7));
}
OUTPUT : omputer
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)
[Link]([Link](7,10));
OUTPUT: omp
12.13 toLowerCase():
{
String str=”PALAR COMPUTER CETNRE”;
[Link]([Link]());
}
12.14 toUpperCase( ):
[Link]([Link]());
12.15 replace(ch1,ch2)
This method is used to replace all occurance of ch1, with another character ch2 in the
current object.
{
[Link](“Palar Computer Centre”);
[Link]([Link](‘a’,’e’));
}
OUTPUT : peler computer center
class Str
{
public static void main(String args[])
{
String str=new String("Palar computer");
//or
String str1="palar computer";
[Link](str);
[Link](str1);
[Link]("Length = "+[Link]( ));
[Link] ("Index Of o ="+[Link]('o'));
[Link]("Index of put = "+[Link]("put"));
[Link]("char at pos. 3 ="+[Link](3));
[Link]("Str = str1 ="+[Link](str1));
[Link]("ignore Str = str1 ="+[Link](str1));
[Link]("Strat at palar ="+[Link]("palar"));
[Link]("sub string of 7 = "+[Link](7));
[Link]("sub string of 7 to 10 = "+[Link](7,10));
[Link]("Lower Case = "+[Link]());
[Link]("Upper case = "+[Link]());
[Link]("Replace a to e = "+[Link]('a','e'));
[Link](str);
}
}
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(“palar computer”);
[Link](str);
}
}
OUTPUT : palar computer
12.2.1 length( )
{
StringBuffer str=new StringBuffer(“palar computer centre”);
[Link]([Link]( ))
}
OUTPUT : 21
12.2.2 charAt(i)
0OUTPUT : palar
12.2.3 append(char)
The method is used to add a character ‘ch’ to the String buffer.
{
StringBuffer str=new StringBuffer(“palar computer”);
[Link]([Link](‘s’));
[Link](str);
}
OUTPUT : palar computers
{
[Link]([Link]("centre"));
[Link](str);
}
OUTPUT : palar computers centre
12.2.5 insert(i,ch)
This method is used to insert a character ‘ch’ at the index position ‘i’.
{
StringBuffer str;
[Link]([Link](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(“palar computer”);
[Link](7,’r’);
[Link](str);
}
class StrBuff
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("palar computer");
[Link](str);
[Link]("Length = "+[Link]( ));
[Link]("Char at 2 is "+[Link](2));
[Link]("Append s = "+[Link]('s'));
[Link]("Append Centre "+[Link](" centre"));
[Link]("Insert r to 7th position =
"+[Link](7,'r'));
[Link]("Reverse "+[Link]( ));
[Link](7,'z');
[Link]("Set r to 7th poisition = "+str);
}
}
13. [Link] :
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, Collec
4. ArrayList. tion
5. Arrays
6. LinkedList,
7. Stack,
8. Vector,
9. Date, Set List
10. AbstractSet,
11. HashSet,
12. Hashtable
13. TreeSet etc., SortedSet
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.
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.
Program:
// Demonstrate ArrayList.
import [Link].*;
class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
[Link]("Initial size of al: " +
[Link]());
class ArrayListToArray
{
public static void main(String args[])
{
// Create an array list
ArrayList al = new ArrayList();
// get array
Object ia[] = [Link]();
int sum = 0;
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.
Program:
import [Link];
class LikedListDemo2
{
public static void main(String args[])
{
LinkedList l1=new LinkedList();
[Link](“A”);
[Link](“B”);
[Link](“C”);
[Link](l1);
[Link](1,”D”);
[Link](l1);
[Link](“E”);
[Link](l1);
[Link](“F”);
[Link](l1);
[Link](“B”);
[Link](l1);
[Link]( );
[Link](l1);
[Link]( );
[Link](l1);
[Link]([Link]( ));
[Link]([Link]( ));
[Link]([Link]( ));
}
}
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 [Link].*;
class LinkedListDemo2 {
public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
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()
Program:
// Demonstrate HashSet.
import [Link].*;
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)
[D,E,K,P,R,Z]
[E,K,P,R,Z]
Program:
// Demonstrate TreeSet.
import [Link].*;
class TreeSetDemo2
{
public static void main(String args[])
{
// Create a tree set
TreeSet ts = new TreeSet();
[Link](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,
return false.
Boolean Return the index of the previous element. If ther is not
hasPerviousIndex() 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 [Link].*;
class IteratorDemo
{
public static void main(String args[])
{
// create an array list
ArrayList al = new ArrayList();
Java 2 added a new class to [Link]. 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 [Link].*;
class BinaryArray
{
public static void main(String args[])
{
int a[]={90,25,10,30,15,60,95,100};
int i;
[Link](a);
for(i=0;i<[Link];i++)
{
[Link](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:
[Link](array,value);
[Link].*;
class ArraySort
{
public static void main(String args[])
{
int a[]={90,100,75,60,10,95,25,80};
int i ;
[Link](a);
[Link]([Link](a,75));
}
}
OUTPUT 3.
3. equals( ): Equals method returns true if 2 arrays are equals otherwise it returns
false.
Program:
import [Link].*;
class ArrayEquals
{
public static void main(String args[])
{
int a[]={90,100,75,60};
int b[]={90,100,75,60};
[Link]([Link](a,b));
}
}
OUTPUT: True.
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
class VectorDemo
{
public static void main(String args[])
{
[Link](new Integer(1));
[Link](new Integer(2));
[Link](new Integer(3));
[Link](new Integer(4));
if([Link](new Integer(3)))
[Link]("Vector contains 3.");
[Link]("\nElements in vector:");
while([Link]())
[Link]([Link]() + " ");
[Link]();
}*/
}
}
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 [Link].*;
class HashTableDemo
{
public static void main (String args[])
{
Hashtable h=new Hashtable( );
[Link](“100”,”kumar”);
[Link](“101”,”Rangan”);
[Link](“102”,”Ram”);
[Link](“103”,”Sri”);
[Link]([Link](“102”));
[Link](h);
}
}
OUTPUT:
Ram
{103 Sri 102 Ram 101=Rangan100=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.
Program:
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)
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 [Link];
class STDemo
{
static String in = "title=Java: The Complete Reference;" +
"author=Naughton and Schildt;" +
"publisher=Osborne/McGraw-Hill;" +
"copyright=1999";
while([Link]())
{
String key = [Link]();
String val = [Link]();
[Link](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)
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([Link](dob))
[Link]("Entry dates are correct ");
else
[Link]("Pls. Enter Doj date after dob date ");
}
}
14. IO package :
The [Link] provides Classes and Interfaces that supports for input and
output Operations.
import [Link].*;
class DataInputDemo
{
public static void main(String args[])throws IOException
{
DataInputStream ds=new DataInputStream([Link]);
String str;
int n1,n2,n3;
[Link](“Enter the first no:”);
str=[Link]( );
n1=[Link](str);
[Link](“Enter the second no:”);
str=[Link]( );
n2=[Link](str);
n3=n1+n2;
[Link](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.
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 [Link].*;
class FileDemo
{
static void P(String s)
{
[Link](s);
}
public static void main(String arg[])
{
File f1= new File("/subhjava/[Link]");
P("File name : " + [Link]());
P("Path : "+[Link]());
P("Abs Path : "+[Link]());
P("Parent : "+[Link]());
P([Link]() ? "Exists " : "does not Exist ");
P([Link] () ? "is writeable " : "is not writeable");
P([Link] () ? "is readable " :" is not readable");
P("is " + ([Link]() ? "directory ": "Not a
directory "));
P("is " + ([Link]() ? "Hidden ": "Not Hidden"));
P([Link]() ? "Normal file " : "might be a named pipe");
P([Link] () ? "is obsolute " : " is not absolute ");
P("File last modified : "+[Link]());
P("file size : "+[Link]() + "Bytes");
}
}
import [Link].*;
class FileRename
{
public static void main(String args[])
{
File f1=new File(“c:/palar/kumar”);
File f2=new File(“c:/palar/prakash”);
[Link](f2);
}
}
11. list ( ):-
It returns all the files and directories of the invoking object.
import [Link].*;
class FileList
{
public static void main(String args[])
{
int i;
File f=new File(“e:/newjava”);
String str[]=[Link]();
for(i=0;i<[Link];i++)
{
[Link](str[i]);
}
}
}
import [Link].*;
class MakeDirectory
{
public static void main(String args[])
{
File f1=new File(“c:\India”);
[Link]();
}
}
13. delete( ):
It is used to delete the file (given).
import [Link].*;
class FileDelete
{
public static void main(String args[])
{
File f1=new File(“c:/India”);
[Link]( );
}
}
14.3 Streams
Java program perform I/O through streams. A stream is an abstraction that
either produces or consumes information. A stream is linked to a physical device by
the java I/O systems.
All streams behave in the same manner, even if the actual physical devices to
which they are linked differ.
Ie., an input stream can get from many different kinds of input devices like:
hard disk, a keyboard, or a network socket. And, also for output stream.
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.
import [Link].*;
class FileOpen
{
public static void main(String arg[]) throws IOException
{
FileInputStream fr = new FileInputStream(arg[0]);
int s;
while((s=[Link]())!=-1)
{
[Link]((char)s);
}
[Link]();
}
}
import [Link].*;
class FileWrite
{
public static void main(String args[]) throws IOException
{
InputStreamReader kb=new InputStreamReader([Link]));
import [Link].*;
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) {
[Link]("Input File Not Found");
return;
}
// Copy File
try {
/* do {
i = [Link]();
if(i != -1)
[Link](i);
} while(i != -1);*/
while((i=[Link]())!=-1)
[Link](i);
} catch(IOException e) {
[Link]("File Error");
}
[Link]();
[Link]();
}
}
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 palar;
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 palar;
public class General
{
public int fact(int n)
{
int i, f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
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 palar.*;
class AccessPalar
{
public static void main(String args[])
{
General g= new General();
[Link]([Link](20,10));
[Link]([Link](5));
}
}
OUTPUT :
200
120
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-based multitasking is the feature that allow your
computer to turn two or more programs concurrently.
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.
Method Meaning
Program:
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
{
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
[Link]( );
}
catch(Exception e)
{
[Link](“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
{
[Link]( );
if([Link]())
[Link]("First Thread is running");
[Link]( );
if([Link]())
[Link]([Link]( ));
else
[Link]("First Thread finished");
[Link]( );
[Link]( );
}
catch(Exception e)
{
[Link](“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
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)
{
[Link]("[" + msg);
try
{
[Link](1000);
}
catch(InterruptedException e)
{
[Link]("Interrupted");
}
[Link](" ]");
}
}
class Synch
{
}
}
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 [Link] 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
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 [Link];
import [Link].*;
public class AppletDemo extends Applet
{
public void paint(Graphics g)
{
[Link](“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 ()
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
[Link].
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.
repaint( ) update( )
paint( )
Program:
import [Link].*;
import [Link].*;
public class AppletLifeDemo extends Applet
{
public void init( )
{
[Link](“Executing init method”);
}
public void start( )
{
[Link](“Executing start method”);
}
public void paint(Graphics g)
{
[Link](“welcome to java”,100,100);
}
public void stop( )
{
[Link](“Executing stop method”);
}
public void destroy( )
{
[Link](“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);
17.5 Colors in java
Program:
import [Link].*;
import [Link].*;
public class AppletColorDemo extends Applet
{
public void paint(Graphics g)
{
setBackground([Link]);
setForeground([Link]);
[Link](“Welcome To Java Applet”,100,100);
}
}
Syntax:
import [Link].*;
import [Link].*;
//<applet code=AppletColor width=300 height=300 ></applet>
public class AppletColor extends Applet
{
public void paint(Graphics g)
{
Color c1=new Color(255,204,204);
Color c2=new Color(255,0,0);
setBackground(c1);
setForeground(c2);
[Link](“welcome to Java”,100,100);
}
}
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 [Link].*;
import [Link].*;
public class AppletDraw1 extends Applet
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](100,100,150,200);
}
}
OUTPUT :
The drawRect and fillRect methods displayed an outlined and filled rectangle
respectively.
Syntax:
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 [Link]. The diameter of
the rounding are along the y-axis is specified by [Link].
Program:
import [Link].*;
import [Link].*;
public class AppletDraw2 extends Applet Output :
{
public void paint(Graphics g)
{
[Link]([Link]);
[Link](50,50,50,20);
[Link]([Link]);
[Link](100,100,50,20);
[Link]([Link]);
[Link](150,150,50,20,5,55);
[Link]([Link]);
[Link](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 [Link].*;
import [Link].*;
public void paint(Graphics g) O/p:
{
[Link]([Link]);
[Link](100,100,200,200);
}
17.6.4 Drawing Arcs:
Syntax:
drawArc(int x1,int y1, int width, int height, int [Link], int [Link]);
fillArc(int x1,int y1, int width, int height, int [Link],int [Link])
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.
[Link], [Link],[Link].
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 [Link].*;
import [Link].*;
public class AppletFont extends Applet
{
public void paint(Graphics g)
{
Font f=new Font(“Arial”,[Link]+[Link],25);
[Link](f);
[Link](new Color(255,0,255));
[Link](“Welcome to Java”,150,150);
}
}
17.8 Images:
import [Link];
import [Link].*;
public class ImageDemo extends Applet
{
Image img;
public void init()
{
img=getImage(getCodeBase(),"[Link]");
}
public void paint(Graphics g)
{
[Link](img,10,10, this);
}
}
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:
[Link](instanceof Myclass);
Eg:
[Link](this);
3. code that implements the methods in the listener interface. For example
the single argument to the method is an ActionEvent object that gives information
about the event and its source.
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 [Link].*;
import [Link].*;
import [Link].*;
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”;
repaint( );
}
public void mouseExited (MouseEvent me)
{
msg = “Mouse Exited “;
repaint( );
}
public void paint(Graphics g)
{
[Link](msg,100,100);
}
}
2. MouseMotionListener interface:
Program:
Program:
import [Link].*;
import [Link].*;
import [Link].*;
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)
{
[Link](msg,100,100);
}
}
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 [Link] class. The
elements of the Userinface are called components. These components are derived
from the [Link] 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
Applet
Panel
Panel
Object
Object Component
Component Container
Container Frame
Frame
Window
Window
Dialog
Dialog
Frame
Frame
Button
Button
Checkbox
Checkbox
Object
Object Component
Component
TextArea
TextArea
Text Component
Text Component
TextField
TextField
Choice
Choice
List
List
Label
Label
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 [Link] and height [Link]
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 [Link].*;
import [Link].*;
public class LabelDemo extends Applet
{
public void paint(Graphics g)
{
Label l1=new Label (“Palar”);
Label l2=new Label (“Vellore”);
add(l1);
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 [Link].*;
import [Link].*;
import [Link].*;
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);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str=[Link]( );
if([Link](“Red”))
setBackground([Link]);
else if([Link](“Green”))
setBackground([Link]);
else if([Link](“Blue”))
setBackground([Link]);
else if([Link](“Pink”))
setBackground([Link]);
else if([Link](“Black”))
setBackground([Link]);
else
setBackground([Link]);
}
}
import [Link].*;
import [Link].*;
import [Link].*;
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);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str=[Link]( );
f= new Font(str,[Link],20);
repaint( );
}
public void paint(Graphics g)
{
[Link](f);
[Link](“Palar Computers”,100,100);
}
}
19.2.3 Text Field:
The textfield class implements a single line text entry area, usually called an edit
control.
import [Link].*;
import [Link].*;
import [Link].*;
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);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str,str1;
str=[Link]();
str1 =[Link]( );
int n1=[Link](str1);
str1 = [Link]( );
int n2= [Link](str1);
int n;
if([Link]("SUM"))
{
n=n1+n2;
[Link](n+"");
}
else if([Link]("SUB"))
{
n=n1-n2;
[Link](n+" ");
}
else if([Link]("DIV"))
{
n=n1/n2;
[Link](n+" ");
}
else if([Link]("MOD"))
{
n=n1%n2;
[Link](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
setEchoChar.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
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);
[Link](‘*’);
Button b1 = new Button(“Login”);
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str1=[Link]( );
String str2= [Link]( );
if([Link](“palar”) && [Link](“admin”))
msg=”User name and password are correct”;
else
msg=”invalid username or password”;
repaint( );
}
public void paint(Graphics g)
{
[Link](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 [Link].*;
import [Link].*;
import [Link].*;
public class TextAreaDemo extends Applet
{
public void init( )
{
TextArea t1= new TextArea(10,15);
add(t1);
}
}
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 [Link].*;
import [Link].*;
import [Link].*;
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 [Link].*;
import [Link].*;
import [Link].*;
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);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
if([Link]( ) == c1)
setForeground([Link]);
else if ([Link]( ) == c2)
setForeground([Link]);
else if ([Link]( ) == c3)
setForeground([Link]);
else if ([Link]( ) == c4)
setForeground([Link]);
else
setForeground([Link]);
repaint( );
}
public void paint(Graphics g)
{
Font f= new Font("Arial",[Link],25);
[Link](f);
[Link](“Palar 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 [Link].*;
import [Link].*;
import [Link].*;
public class ChoiceDemo extends Applet implements ItemListener
{
Choice c;
public void init( )
{
c = new Choice();
[Link](“Red”);
[Link](“Green”);
[Link](“Pink”);
[Link](“Blue”);
[Link](“Gray”);
add (c);
[Link](this);
}
public void itemStateChanged(ItemEvent e)
{
String str=[Link]( );
if([Link](“Red”))
setBackground([Link]);
else if ([Link](“Green”))
setBackground([Link]);
else if([Link](“Pink”))
setBackground([Link]);
else if ([Link](“Blue”))
setBackground([Link]);
else
setBackground([Link]);
}
}
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 [Link].*;
import [Link].*;
public class ListDemo extends Applet implements ItemListener
{
List l;
public void init( )
{
l = new List (4);
[Link](“Red”);
[Link](“Green”);
[Link](“Pink”);
[Link](“Gray”);
[Link](“Magenta”);
[Link](“Blue”);
add (l);
[Link](this);
}
public void itemStateChanged(ItemEvent ie)
{
String str=[Link]( );
if([Link](“Red”))
setBackground([Link]);
else if ([Link](“Green”))
setBackground([Link]);
else if ([Link](“Pink”))
setBackground([Link]);
else if ([Link](“Gray”))
setBackground([Link]);
else if ([Link](“Magenta”))
setBackground([Link]);
else
setBackground([Link]);
}
}
20. Layout Management
The Layout Management classes are a set of classes that implement the
[Link] 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
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 [Link].*;
}
}
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, int Creates a grid layout with the specified rows
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
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 [Link].*;
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.
Eg: add("East",mybutton);
Program:
import [Link].*;
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
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 [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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",[Link],20);
head = new Label("Result Sheet");
[Link](f);
[Link]([Link]);
h = new Panel();
[Link](new FlowLayout());
[Link](head);
p1=new Panel();
[Link](new GridLayout(4,2));
[Link](l1);
[Link](t1);
[Link](l2);
[Link](t2);
[Link](l3);
[Link](t3);
[Link](l4);
[Link](t4);
[Link](l5);
[Link](t);
[Link](l6);
[Link](a);
[Link](l8);
[Link](r);
[Link](l7);
[Link](g);
p2=new Panel();
[Link](new FlowLayout([Link]));
[Link](b1);
p3=new Panel();
[Link](new GridLayout(3,1));
[Link](h);
[Link](p1);
[Link](p2);
add(p3);
[Link](20,20,200,200);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
String s=[Link]();
int m1=[Link](s);
s=[Link]();
int m2=[Link](s);
s=[Link]();
int m3=[Link](s);
int t=m1+m2+m3;
float a=[Link]((float)t/(float)3.0);
[Link](a);
String strtot=new String(t+"");
[Link]();
[Link](strtot);
char chtot[];
chtot=[Link]();
StringBuffer str = new StringBuffer();
int i=0;
[Link]("Printing in words ....");
try
{
while(i<[Link])
{
[Link](chtot[i]+"");
switch(chtot[i])
{
case '1': [Link](" One");
break;
case '2': [Link](" Two");
break;
case '3': [Link](" Three");
break;
case '4': [Link](" Four");
break;
case '5': [Link](" Five");
break;
case '6': [Link](" Six");
break;
case '7': [Link](" Seven");
break;
case '8': [Link](" Eight");
break;
case '9': [Link](" Nine");
break;
case '0': [Link](" Zero");
break;
}
i++;
}
}
catch(Exception e1){ }
[Link](t+" "+str);
[Link](a+"");
[Link](str);
if(m1>=40 && m2>=40 && m3>=40)
{
[Link]("Pass");
if(a>=75)
[Link]("Distinction");
else if(a>=60)
[Link]("First Class");
else if(a>=40)
[Link]("Second Class");
}
else
{
[Link]("Fail");
[Link]("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.
Summary:
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.
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 [Link].*;
import [Link].*;
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.
[Link](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
menu. Each time a menu item is selected, an actionevent is generated. Thus
you must implement ActionListener interface.
Program:
import [Link].*;
import [Link].*;
[Link](f1);
[Link](f2);
[Link](f3);
[Link](bar);
[Link](f4);
[Link](f5);
[Link](f6);
[Link](e1);
[Link](e2);
[Link](e3);
[Link](c1);
[Link](c2);
[Link](c3);
[Link](c4);
[Link](c5);
[Link](file);
[Link](edit);
[Link](color);
setMenuBar(mbr);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str = [Link]( );
if([Link](“Red”))
setBackground([Link]);
else if([Link](“Green”))
setBackground([Link]);
else if([Link](“Blue”))
setBackground([Link]);
else if([Link](“Pink”))
setBackground([Link]);
else
setBackground([Link]);
}
}
class MenuDemo
{
public static void main(String args[])
{
Myframe mf = new Myframe( );
[Link](300,300);
[Link](true);
}
}
Program:
import [Link].*;
import [Link].*;
class MyMenu extends Frame implements ActionListener
{
Font f;
MyMenu ( )
{
super(“Font Menu”);
MenuBar mbr=new MenuBar( );
[Link](c1);
[Link](c2);
[Link](c3);
[Link](c4);
[Link](c5);
[Link](fn1);
[Link](fn2);
[Link](fn3);
[Link](fn4);
[Link](fn5);
[Link](fs1);
[Link](fs2);
[Link](fs3);
[Link](fs4);
[Link](fs5);
[Link](s1);
[Link](s2);
[Link](s3);
[Link](s4);
[Link](s5);
[Link](color);
[Link](fname);
[Link](fstyle);
[Link](fsize);
[Link](file);
[Link](edit);
[Link](format);
setMenubar(mbr);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
f = new Font(“Times New Roman”,[Link],20);
}
public void actionPerformed(ActionEvent ae)
{
String str = [Link]( );
if([Link](“Red”))
setBackground([Link]);
else if([Link](“Green”))
setBackground([Link]);
else if([Link](“Pink”))
setBackground([Link]);
else if([Link](“Magenta”))
setBackground([Link]);
else if([Link](“Times New Roman”))
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 [Link].*;
import [Link].*;
[Link](this);
[Link](this);
f=new Font("Times New Roman",[Link],20);
}
public void actionPerformed(ActionEvent ae)
{
String str=[Link]();
if([Link]("Red"))
setForeground([Link]);
else if([Link]("Green"))
setForeground([Link]);
else if([Link]("Blue"))
setForeground([Link]);
else if([Link]("Pink"))
setForeground([Link]);
else if([Link]("Magenta"))
setForeground([Link]);
else if([Link]("24"))
f = new Font([Link]( ),[Link]( ),24);
else if([Link]("28"))
f= new Font([Link]( ),[Link]( ),28);
else if([Link]("32"))
f = new Font([Link]( ),[Link]( ),32);
else if([Link]("36"))
f = new Font([Link]( ),[Link]( ),36);
else if([Link]("40"))
f = new Font([Link]( ),[Link]( ),40);
repaint( );
}
public void itemStateChanged(ItemEvent ie)
{
if([Link]( )== true && [Link]( ) ==false)
f=new Font([Link]( ),[Link],[Link]( ));
else if([Link]( )== false && [Link]( )==true)
f=new Font([Link]( ),[Link],[Link]( ));
else if([Link]( )== true && [Link]( )==true)
f=new Font([Link]( ),[Link]+[Link],[Link]( ));
else
f=new Font([Link]( ),[Link],[Link]( ));
repaint();
}
public void paint(Graphics g)
{
[Link](f);
[Link]("Welcome to Java",100,100);
}
}
class CMenu
{
public static void main(String args[])
{
Myframe mf= new Myframe( );
[Link](300,300);
[Link](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 [Link].*;
import [Link].*;
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”);
[Link](c1);
[Link](c2);
[Link](c3);
[Link](d);
[Link](c4);
[Link](c5);
}
class Mouse extends MouseAdapter
{
public void mouseClicked(MouseEvent me)
{
[Link]([Link](),[Link](),[Link]( ));
}
}
public void actionPerformed(ActionEvent ae)
{
String str = [Link]( );
if([Link](“Red”))
setBackground([Link]);
else if([Link](“Blue”))
setBackground([Link]);
else if([Link](“Green”))
setBackground([Link]);
else if([Link](“Pink”))
setBackground([Link]);
else
setBackground([Link]);
}
}
class PopMenuDemo
{
public static void main(String args[])
{
Popup mf= new Popup( );
[Link](300,300);
[Link](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.
A dialog box can be made modal. A modal dialog prevents user input to other
windows in the application until dialog is closed.
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
[Link] and [Link].
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 [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class Editor extends Frame
{
String filename;
TextArea tx ;
Clipboard clip=getToolkit().getSystemClipboard();
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");
[Link](new New());
[Link](n);
[Link](new Open());
[Link](o);
[Link](new Save());
[Link](s);
[Link](new Exit());
[Link](e);
[Link](F);
Menu E=new Menu("Edit");
MenuItem cut=new MenuItem("Cut");
MenuItem copy=new MenuItem("Copy");
MenuItem paste=new MenuItem("Paste");
[Link](new Cut());
[Link](cut);
[Link](new Copy());
[Link](copy);
[Link](new Paste());
[Link](paste);
[Link](E);
setMenuBar(mb);
}
catch(Exception ex)
{
[Link]("File not found");
}
[Link]();
}
}
}
class Exit implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
[Link](0);
}
}
void ReadFile()
{
BufferedReader d;
StringBuffer sb=new StringBuffer();
try
{
d=new BufferedReader(new FileReader(filename));
String line;
while((line=[Link]())!=null)
[Link](line+"\n");
[Link]([Link]());
[Link]();
}
catch(FileNotFoundException fe)
{
[Link]("File not found");
}
catch(IOException ioe)
{
}
}
class Cut implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sel=[Link]();
StringSelection ss=new StringSelection(sel);
[Link](ss,ss);
[Link]("
",[Link](),[Link]());
}
}
class Copy implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String sel=[Link]();
StringSelection clipString=new StringSelection(sel);
[Link](clipString,clipString);
}
}
class Paste implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Transferable cliptran=[Link]([Link]);
try
{
String sel=(String)
[Link]([Link]);
[Link](sel,[Link](),[Link]
tionEnd());
}
catch(Exception exc)
{
[Link]("Not String flavor");
}
}
}
public static void main(String args[])
{
Frame f=new Editor();
[Link](500,400);
[Link](true);
[Link]();
}
}
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 componets facilitate efficient graphical user interface(GUI) development. These
components are a collection of lightweight visual components. Swing components
contain a replacement for the heavyweight AWT components as well as complex
user-interface components such as trees and tables.
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
JToggleB JMenu
utton Bar
JRadio JCheck
Button Box JCheckBox JMenu JRadioButton
Menu Item MenuItem
Windows
Applet
JApplet
JDialog JFrame
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.
Syntax : To Display Input Box.
[Link](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 [Link].*;
class Jop
{
public static void main (String args[])
{
String str;
int a,b,c;
try
{
str = [Link]("Enter the 1st no: ");
a = [Link](str);
str = [Link]("Enter the 2nd no: ");
b = [Link](str);
c = a+b;
[Link](null,"SUM " +c, "Result Box",
JOptionPane. INFORMATION_MESSAGE);
}
catch(Exception e)
{
[Link](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 [Link].*;
import [Link].*;
class Myframe extends JFrame
{
Myframe()
{
super(“Frame Window”);
}
public void paint(Graphics g)
{
setBackground([Link]);
[Link](“Welcome to java”,100,100);
[Link](100,100,50,50);
}
}
class JFrameDemo
{
public static void main(String args[])
{
Myframe mf = new Myframe( );
[Link](300,300);
[Link](true);
}
}
23.3.3 JPanel:
JPanel is a generic lightweight container. JPanel can be used as a dedicated
drawing area that can receive new events and if often extended to create new
components.
Syntax
JPanel panelobj = new JPanel( );
Syntax :
[Link](panelobj);
23.3.4 JLabel:
Syntax
JLabel obj = new JLabel (String str);
Program:
import [Link].*;
import [Link].*;
class Mypanel extends JFrame
{
Mypanel ( )
{
super(“Label Demo”);
JPanel jp = new JPanel( );
Font f= new Font("Verdana",[Link],20");
JLabel L1= new JLabel(“Welcome to JFC Swing“);
[Link](f);
[Link](L1);
getContentPane().add(jp);
}
}
class JLableDemo
{
public static void main (String args[])
{
Mypanel mf = new Mypanel ( );
[Link](300,300);
[Link](true);
}
}
23.3.5 JButton:
Syntax: JButton obj = new JButton (String name);
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.
[Link] Adding Tool Tips:
Tool tips are short informative messages that you see when you reset the
mousecursor on a button.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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");
[Link]('r');
[Link]('g');
[Link]('b');
[Link]('p');
[Link]('m');
[Link]("set red background color");
[Link]("set green background color");
[Link]("set blue background color");
[Link]("set pink background color");
[Link]("set magenta background color");
[Link](b1);
[Link](b2);
[Link](b3);
[Link](b4);
[Link](b5);
getContentPane( ).add(jp);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str = [Link]( );
if([Link]("red"))
[Link]([Link]);
else if([Link]("green"))
[Link]([Link]);
else if([Link]("blue"))
[Link]([Link]);
else if([Link]("pink"))
[Link]([Link]);
else
[Link]([Link]);
}
public static void main(String arg[])
{
MyButton mb = new MyButton();
[Link](400,150);
[Link](true);
[Link](200,200);
}
}
Program:
import [Link].*;
import [Link].*;
import [Link].*;
class MyImage extends JFrame
{
MyImage ( )
{
super(“ImageButton”);
JPanel jp = new JPanel( );
JButton b1 = new JButton(“Image”);
Program:
import [Link].*;
import [Link].*;
import [Link].*;
[Link]([Link],[Link]);
Border line4 = [Link]([Link],5);
[Link](line1);
[Link](line2);
[Link](line3);
[Link](line4);
[Link](l1);
[Link](l2);
[Link](l3);
[Link](l4);
getContentPane().add(jp);
getContentPane().add(jp);
}
}
class BorderDemo1
{
public static void main(String args[])
{
Mybrd mf = new Mybrd( );
[Link]( 300,300);
[Link](true);
}
}
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
Program:
23.6 JColorChooser:
One of the newer feature of Java is the predefined GUI Component JColorChooser
for selecting colours.
Syntax :
[Link](this,String title,default Color);
Program:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class MyColor extends JFrame implements ActionListener
{
JPanel jp;
Jbutton b1;
MyColor ()
{
super(“Color Chooser”);
b1 = new JButton(“Color”);
[Link](b1);
[Link](this);
getContentPane( ).add(jp);
}
}
public void actionPerformed(ActionEvent ae)
{
Color c;
c= [Link](this,”Color Box”,[Link]);
[Link](c);
}
}
class JColorChooserDemo
{
public static void main(String args[])
{
MyColor me = new MyColor ( );
[Link](300,300);
[Link](true);
}
}
23.7 JTextField:
Program:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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”);
[Link](l1);
[Link](t1);
[Link](l2);
[Link](t2);
[Link](t3);
[Link](l3);
[Link](t3);
[Link](b1);
[Link](this);
getContentPane( ).add(jp);//add panel to the JFrame
}
public void actionPerformed(ActionEvent ae)
{
String str;
int n1,n2,n3;
str = [Link]( );
n1 = [Link](str);
str = [Link]( );
n2 = [Link](str);
n3 = n1+n2;
[Link](n3+ “ “);
}
}
class JTextFieldDemo
public static void main(String args[])
{
MyText mf = new MyText( );
[Link](300,300);
[Link](true);
}
}
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 [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
if([Link]("Ok"))
{
String uname=[Link]();
uname=[Link]();
String pass=[Link]();
if([Link]("palar") && [Link]("admin"))
{
if([Link]("Close"))
{
[Link](0);
dispose();
}
}
}
class Jpass
{
public static void main(String args[])
{
Mypass mf = new Mypass( );
[Link](300,300);
[Link](true);
}
}
23.8 JCheckBox:
Program:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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”);
[Link](t1);
[Link](c1);
[Link](c2);
[Link](this);
[Link](this);
getContentPane().add(jp);
}
public void itemStateChanged(ItemEvent ie)
{
Font f;
if([Link]( ) == true && [Link] ( ) == 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 [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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”);
[Link](c1);
[Link](c2);
[Link](c3);
[Link](c4);
[Link](c5);
[Link](c6);
[Link](c1);
[Link](c2);
[Link](c3);
[Link](c4);
[Link](c5);
[Link](c6);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
getContentPane( ).add(jp);
}
public void itemStateChanged(ItemEvent ie)
{
if([Link] ( ) == c1)
[Link]([Link]);
else if([Link]( ) == c2)
[Link]([Link]);
else if([Link]( ) == c3)
[Link]([Link]);
else if([Link]( ) == c4)
[Link]( [Link]);
else
[Link]([Link]);
}
}
class JRadioDemo
{
public void main(String args[])
{
MyRadio mf = new MyRadio ( );
[Link]( );
[Link](true);
}
}
23.10 JCombobox:
Program:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Mycombo extends JFrame implements ItemListener
{
JPanel jp;
JCombobox col;
Mycombo
{
super (“Jcombo Demo”);
jp = new JPanel ( );
col = new JCombobox();
[Link](“Red”);
[Link](“Green”);
[Link](“Blue”);
[Link](“Pink”);
[Link](“Magenta”);
[Link](“Yellow”);
[Link](col);
[Link](this);
getContentPane( ).add(jp);
}
public void ItemStateChanged (ItemEvent ie)
{
int n = [Link]( );
if(n == 0)
[Link]([Link]);
else if(n == 1)
[Link]([Link]);
else if(n == 2)
[Link]([Link]);
else if(n == 3)
[Link](Color. Yellow);
}
}
class JComboboxDemo
{
public static void main(String args[ ])
{
Mycombo mf = new Mycombo ( );
[Link](300,300);
[Link](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 [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
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);
Border line2 =
[Link]([Link]);
[Link](line2);
[Link](col);
getContentPane( ).add(jp);
[Link](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.
[Link] or [Link]
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.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class MySlider extends JFrame implements ChangeListener
{
JPanel jp;
JSlider s1,s2,s3;
MySlider ( )
{
super(“Slider Demo”);
jp = new JPanel( );
s1 = new JSlider([Link],0,255,0);
s2 = new JSlider([Link],0,255,0);
s3 = new JSlider([Link],0,255,0);
[Link](s1);
[Link](s2);
[Link](s3);
[Link](this);
[Link](this);
[Link](this);
getContentPane().add(jp);
}
public void stateChanged(ChangeEvent ce)
{
Color c = new Color([Link]( ),[Link]( ),
[Link]( ));
[Link](c);
}
}
class JSliderDemo
{
public static void main(String args[])
{
MySlider mf = new MySlider ( );
[Link](300,300);
[Link](true);
}
}
23.13 JPopMenu
Many of today’s application provide so called context-sensitive popup menus. In
swing, such menus are created with class JPopMenu.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
class MyPopup extends JFrame implements
ActionListener
{
JPanel jp;
JPopupMenu col;
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");
[Link](c1);
[Link](c2);
[Link](c3);
[Link]();
[Link](c4);
[Link](c5);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
addMouseListener(new press());
addWindowListener(new W());
getContentPane( ).add(jp);
}
public void actionPerformed(ActionEvent ae)
{
String str = [Link]( );
if([Link] ("Red"))
[Link]([Link]);
else if([Link]("Green"))
[Link]([Link]);
else if([Link]("Blue"))
[Link]([Link]);
else if([Link]("Pink"))
[Link]([Link]);
else
[Link]([Link]);
}
class press extends MouseAdapter
{
class Jpop
{
public static void main(String args[])
{
MyPopup mf = new MyPopup ( );
[Link](300,300);
[Link](true);
}
}
23.14 JMenuBar :
This component typically appears at the top of a JFrame, Jwindow and JinternalFrame.
It cannot be added directly of the frame. It can be added only through the JFrame,
Jwindow and JinternalFrame’s root pane. A JMenuBar is a component that can be
added to a container similar to any othe component. It cantinas a set JMenus, with
each JMenu respesented a string within the JMenuBar. When the user clicks one of
the text string, the associated menu pop up under the text string and displays its
menu items.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
[Link](c1);
[Link](c2);
[Link](c3);
[Link](c4);
[Link](c5);
[Link](file);
[Link](edit);
[Link](color);
setJMenuBar(mbr);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
getContentPane().add(jp);
}
public void actionPerformed(ActionEvent ae)
{
String str = [Link]( );
if([Link]("Red"))
[Link]([Link]);
else if([Link]("Green"))
[Link]([Link]);
else if([Link]("Blue"))
[Link]([Link]);
else if([Link]("Pink"))
[Link]([Link]);
else
[Link]([Link]);
}
}
class JMenuDemo
{
public static void main(String args[])
{
MyMenu mf = new MyMenu ( );
[Link](300,300);
[Link](true);
}
}