23uca04 - Java Class Notes
23uca04 - Java Class Notes
Submitted
By
M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
ASST.PROFESSOR
KRISHNAGIRI
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
UNIT – II
Inheritance : Basic concepts - Types of inheritance - Member access rules- Usage of this and
Super Keyword – Method Overloading – Method overriding - Abstract classes - Dynamic method
dispatch - Usage of final keyword. Packages: Definition-Access Protection – Importing Packages.
Interfaces : Definition–Implementation– Extending Interfaces. Exception Handling: try – catch -
throw – throws – finally – Built-in exceptions – Creating own Exception classes.
UNIT – III
Multithreaded Programming : Thread Class – Runnable interface – Synchronization – Using
synchronized methods – Using synchronized statement-Interthread Communication – Deadlock.
I/O Streams: Concepts of streams- Stream classes -Byte and Character stream -Reading console Input
and Writing Console output – File Handling.
UNIT – IV
AWT Controls : The AWT class hierarchy – user interface components – Labels – Button
Text Components - Check Box - Check Box Group - Choice -List Box - Panels – Scroll Pane - Menu -
Scroll Bar. Working with Frame class - Colour - Fonts and layout managers. Event Handling :
Events-Event sources – Event Listeners -Event Delegation Model (EDM) – Handling Mouse and
Keyboard Events - Adapter classes – Inner classes.
UNIT – V
Swing : Introduction to Swing – Hierarchy of swing components. Containers -Top level
containers -JFrame - JWindow - JDialog - JPanel - JButton - JToggleButton - JCheckBox -
JRadioButton - JLabel, JTextField – JtextArea – Jlist – JcomboBox - JScrollPane.
UNIT – I
Introduction: Review of Object-Oriented concepts -History of Java – Java buzzwords -JVM
architecture – Data types – Variables – Scope and life time of variables – arrays – operators -control
statements – type conversion and casting – simple java program – constructors – methods – Static
block -Static Data – Static Method String and String Buffer Classes.
Introduction :
Review of Object-Oriented concepts:
1. Objects
2. Classes
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing
Objects:
➢ Objects are the run-time entities in an object –oriented system. They may represent a person,
place, a bank account, a table of data or any item that the program has to handle.
➢ When a program is executed, the objects interact by sending messages to one another. For
example if “customer’’ and “account’’ are two objects in a program, then the customer may
send a message to the account object requesting for the bank balance. Objects can interact
without having to know details of each other’s data or code. Objects contain code and data to
manipulate that data.
Classes:
➢ The entire set of data and code of an object can be made a user defined data type with the help
of a class. Once a class has been defined, we can create any number of objects belonging to
that class.
➢ Each object is associated with the data of type class with which they are created. A class is thus
a collection of objects of similar type. For example, mango, apple, and orange are members of
class fruit. Classes are user defined data types and behave like the built in types of a
programming language
Fruit mango;
➢ Will create an object mango belonging to the class fruit.
Data Abstraction and Encapsulation:
➢ The wrapping up of data and functions into a single unit is known as Encapsulation. The data is
not accessible to the outside world, and only to those functions, which are wrapped in the class,
can access it. These functions provide a interface between the object’s data and the program.
This insulation of the data from direct access by the program is called data hiding or
information hiding.
➢ Abstraction refers to the act of representing essential features without including the background
details or explanations. They encapsulate all the essential properties of the objects that are to be
created. These attributes are sometimes called data members because they hold information.
The functions that operate on these data are sometimes called methods or member functions.
➢ Since the classes use the concept of data abstraction, they are known as Abstract Data
Type(ADT).
Inheritance:
➢ Inheritance is the process by which objects of one class acquire the properties of objects of
another class .It supports the concept of hierarchical classification. For example, the bird
‘robin’ is a part of the class ‘flying bird’, which is again a part of the class bird.
➢ In OOP, the concept of inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it. This is possible by deriving a new
class from the existing one. The new class will have the combine features of both the classes.
Bird
Object Information
Message
➢ Objects have a life cycle. They can be created and destroyed. Communication with an object is
possible as long as it is alive.
JAVA HISTORY:
Java is a general purpose,object_oriented programming language developed by sun micro
systems of USA in 1991.
Originally called OAK by James Gosling.
Java was designed for development of software for consumer electrnic device like
TVs,VCRs,etc.
Goal→To make a language simple,portable and higly reliable.
Most striking feature of language is a platform_neutral language.
Java is the first programming language that is not tied to any particular hardware or os.
Java can be executed anywhere on any system.
JAVA MILESTONES:
In year of 1990 sun Microsystems develop special software used to manipulate consumer
electronic device name of the team head is James Gosling.
In the year of 1991 the team announced a new language named “oak”.
In the year of 1992 team known as green project team demonstrated application of their new
language to control,a list of home appliances using hand_held device with a tiny
touch_sensitivescreen.
In the year of 1993 green project team came up with idea to develop web application could
run all types of computers connected internet.
In the year of 1994 team developed a web browser called HOTJAVA to locate & run Applet
programs on internet.
In the year of 1995 OAK was renamed “JAVA” due to some legal snags.
It is not an acronym.
In the year of 1996 sun releases JDK1.0.
Sun releases JDK1.1 IN 1997.
✓ javap (java dissembler, which enables us to convert byte code files into a program
✓ description)
✓ jdb (java debugger, which helps us to find errors in our programs)
✓ To create source file using Text Editor.
✓ Source code is converted into HTML using java doc.
✓ Source code is compiled using javac & interpreted using java.
✓ Java debugger jdb is used to find errors. Compiled java code converted into source code using
javap (java dis assembler).
Text Editor
javac
Header Files
javah
Java Class File
java jdb
Java Program
Output
➢ The execution engine comprises the garbage collector and the JIT compiler. The JVM comes in
two flavors − client and server. Both of these share the same runtime code but differ in what
JIT is used. We shall learn more about this later. The user can control what flavor to use by
specifying the JVM flags -client or -server. The server JVM has been designed for long-
running Java applications on servers.
➢ The JVM comes in 32b and 64b versions. The user can specify what version to use by using -
d32 or -d64 in the VM arguments. The 32b version could only address up to 4G of memory.
With critical applications maintaining large datasets in memory, the 64b version meets that
need.
Components of JVM (Java Virtual Machine) Architecture
The following are the main components of JVM (Java Virtual Machine) architecture:
1. Class Loader
➢ The JVM manages the process of loading, linking and initializing classes and interfaces in a
dynamic manner. During the loading process, the JVM finds the binary representation of a
class and creates it.
➢ During the linking process, the loaded classes are combined into the run-time state of the
JVM so that they can be executed during the initialization phase.
➢ The JVM basically uses the symbol table stored in the run-time constant pool for the linking
process. Initialization consists of actually executing the linked classes.
➢ The following are the types of class loaders:
• BootStrap class loader: This class loader is on the top of the class loader hierarchy. It loads
the standard JDK classes in the JRE's lib directory.
• Extension class loader: This class loader is in the middle of the class loader hierarchy and is
the immediate child of the bootstrap class loader and loads the classes in the JRE's lib\ext
directory.
• Application class loader: This class loader is at the bottom of the class loader hierarchy and is
the immediate child of the application class loader. It loads the jars and classes specified by
the CLASSPATH ENV variable.
2. Linking and Initialization
The linking process consists of the following three steps −
• Verification − This is done by the Bytecode verifier to ensure that the generated .class files
(the Bytecode) are valid. If not, an error is thrown and the linking process comes to a halt.
• Preparation − Memory is allocated to all static variables of a class and they are initialized
with the default values.
• Resolution − All symbolic memory references are replaced with the original references. To
accomplish this, the symbol table in the run-time constant memory of the method area of the
class is used.
• Initialization is the final phase of the class-loading process. Static variables are assigned
original values and static blocks are executed.
3. Runtime Data Areas
➢ The JVM spec defines certain run-time data areas that are needed during the execution of the
program. Some of them are created while the JVM starts up. Others are local to threads and are
created only when a thread is created (and destroyed when the thread is destroyed). These are
listed below −
➢ PC (Program Counter) Register
✓ It is local to each thread and contains the address of the JVM instruction that the thread is
currently executing.
➢ Stack
✓ It is local to each thread and stores parameters, local variables and return addresses during
method calls. A StackOverflow error can occur if a thread demands more stack space than is
permitted. If the stack is dynamically expandable, it can still throw OutOfMemoryError.
➢ Heap
✓ It is shared among all the threads and contains objects, classes' metadata, arrays, etc., that are
created during run-time. It is created when the JVM starts and is destroyed when the JVM
shuts down.
✓ You can control the amount of heap your JVM demands from the OS using certain flags (more
on this later). Care has to be taken not to demand too less or too much of the memory, as it has
important performance implications. Further, the GC manages this space and continually
removes dead objects to free up the space.
➢ Method Area
✓ This run-time area is common to all threads and is created when the JVM starts up. It stores
per-class structures such as the constant pool (more on this later), the code for constructors and
methods, method data, etc.
✓ The JLS does not specify if this area needs to be garbage collected, and hence,
implementations of the JVM may choose to ignore GC. Further, this may or may not expand as
per the application's needs. The JLS does not mandate anything with regard to this.
DATA TYPES:
➢ Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
➢ Java Primitive Data Types
➢ In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
➢ There are 8 types of primitive data types:
✓ boolean data type
✓ byte data type
✓ char data type
✓ short data type
✓ int data type
✓ long data type
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
JAVA VARIABLES:
➢ A variable is a container which holds the value while the Java program is executed. A variable
is assigned with a data type.
➢ Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
➢ A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location. It is a combination of "vary + able" which means its value can be
changed.
OPERATORS:
➢ It is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
➢ Operators are used in programs to manipulate data & variables.
o Arithmetic operators
o Relational operators
o Logical operators
o Assignment operators
o Increment & decrement operators
o Conditional operators
o Bitwise operators
o Special operators
1.ARITHMETIC OPERATORS:
The operators that works on numbers are called arithmetic operators.
+ addition
- subtraction
* multiplication
/ division
% modulo(It is used to give the reminder value )
Integer Arithmetic:
✓ We use integer values in the arithmetic expression is called integer arithmetic.
✓ Always yields Integer values.
Eg:
A=5,b=3
Expression value
A+b 8
a-b 2
a*b 15
a/b 1 (decimal point truncated)
a%b 2
Eg program
/*calculate months &days*/
class month
public static void main(String args[])
{
int months, days=700;
System.outprintlnf(“enter the days”);
months=days/30;
days=days%30;
System.out.printlnf(“months”+ months+”days”+days);
}
Real Arithmetic:
✓ The arithmetic operation involves only real numbers is called real arithmetic.
✓ It may have values either in decimal or expression notation.
A=5.5,b=2.0
Expression value
A+b 7.0
a-b 3.0
a*b 10.0
a/b 2.75
Mixed mode Arithmetic:
When one of the operands is real & other is integer .
Eg 15/10.0=1.5
2.RELATIONAL OPERATORS:
These operators are used to compare two or more quantities. the result is either true or false.
Operators meaning
< is less than
<= is less than or equal to
< is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
General format:
3.LOGICAL OPERATOR:
✓ The logical operator is used to test more than one condition.
Logical Operator Meaning
&& logical AND
|| logical OR
! logical NOT
0 0 0 0 0 1
0 1 0 1 1 0
1 0 0 1
1 1 1 1
4. ASSIGNMENT OPERATOR:
✓ The assignment operator is used to assign the values to the operand.
✓ General format:
Variable operand = expression
Shorthand Assignment:
The shorthand assignment operator is op=.
Op->operator.
Statement with simple statement with shorthand
Assignment operator operator
a=a+1 a+=1;
a=a-1 a-+1;
a=a*(n+1) a*=n+1;
Advantages:
• The statement more concise and easier to read.
• The left-hand side variable need not to repeated on the right-hand side.
• The statement is more efficient.
5. INCREMENT AND DECREMENT OPERATOR:
The increment is operator (++) add one and decrement operator(--) is subtract one.
Eg.
++m =>m=m+1=>m+=1.
M++=>m=m+1=>m+=1.
In general m++,++m are same but when they are used in assignment statement they have
different meanings.
If the operator placed before the operand it is known as preincrement operator.if the operator
placed following the operand it is known as post increment operator.
For eg.
M=5 m=5;
Y=++m; y=m++;
Y=6,m=6. y=5,m=6.
A prefix operator first adds 1 to the operand and then the result is assigned to the variable on
left.
A postfix operator first assign the value to the variable on left and then increment the operand.
6. CONDITIONAL OPERATOR:
✓ It is a ternary operator and takes three operands. The “?:” is joinly known as conditional
operator.
General format:
7. BITWISE OPERATOR:
It is used for manipulation of data at bit level.
It may not be applied to float or double.
Operator meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
Bitwise Table:
A B A|B A&B A^B ~A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0
Left Shift:
❖ The Left shift operator <<, shifts all of the bits in a value to the left a specified number of
times.
Value <<m
❖ Here num specifies the number of positions to the left-shift the values in value that is the <<,
moves all of the bits in the specified value to the left by the number of bit positions specified
by num.
Right Shift:
❖ The right shift shifts all of the bits in value to the right a specified number of times. Its general
form
Value >> num.
Int a=32; a=a>>2; a will now have 8.
8. SPECIAL OPERATORS:
1. Comma(,)
2. Sizeof.
3. Pointer(&.*).
4. Member selection(. And->).
Comma Operator:
• It is used to link the releted expression together.
• It is evaluated from left to right.
Eg. value=(n=1,m=10,n+m);
The Sizeof Operator:
• It is compile time operator and when it is used in operand , it the number of bytes the operand
occupies.
Eg M=sizeof(sum).
N=sizeof(longint).
Member Selection Operator:
• It is used to access the instance variables & methods of class objects.
• e.g. Person1.age()
• It is used to access classes & sub_Packages from a packages.
CONTROL STATEMENTS / DECISION MAKING STATEMENTS:
The decision making statement are used to control the flow of execution.
▪ if statement.
▪ switch statement.
▪ conditional operator statement.
if Statement:
➢ It is a decision making statement and is used to take a decision based on a given condition.
The general form is,
if(condition)
{
Statement-1;
}
➢ If the condition is true, the statement-1 will be executed and the control is transferred to the
statement-n. If the condition is false, the block is skipped.
Example:
class positive
{
public static void main(String args[])
{
int a=9;
if(a>0)
System.out.println(“a is positive”);
}
The if statement takes the below forms.
1. if-else statement.
2. nested if-else statement.
3. else if ladder statement.
If-Else Statement:
It is a two way decision making statement; it is used to execute a set of statements based on a
condition.
Execution:
• If conditions-1 is true than condition-2 is check. If condition-2 is true statement-1 will be
executed and the control transferred to statement-n.
}
}
else
{
if(b>c)
{
System.out.println( b);
}
else
{
System.out.println( c);
}
}
Input:
9
6
5
output:
largest number=9
else-if ladder:
➢ It is the multi path decision making statement.
if(condition-1)
{
if(condition1)
Statement-1;
else-if(condition-2)
statement-2;
else-if(condition-3)
statement-3;
………..
…………
}
else
default statement;
Execution:
▪ As soon as a condition is true the statement associated with the condition is executed, and the
control is transferred to statement-n.
▪ If all the n conditions are false the default statement will be executed.
Eg:
/*Write a program to process student results based on the given data.*/
class marklist
{
public static void main(String args[])
{
int m1=89, m2=90, m3=99, m4=90, m5=80;
float avg;
avg=(m1+m2+m3+m4+m5)/5;
System.out.println(“tot”+tot+”avg”+avg);
if(avg>79)
System.out.println(“Distinction”);
else if(avg>59)
System.out.println (“First class”);
else if(avg>49)
System.out.println (“Second class”);
else if(avg>39)
System.out.println (“Third class”);
else
System.out.println (“Fail”);
}
exp1,exp2,exp3-> expressions.
• If expression1 is true, expression 2 is evaluated and value is assigned to left hand side
variable.
• If expression1 is false, expression3 is evaluated and value is assigned to left hand side variable.
• It should be used in an assignment statement.
Eg:
1)/*largest of two numbers*/
class large
{
public static void main(String args[])
{
int a=7,b=6,c;
c=(a>b)?a:b;
System.out.println(c);
}
Switch statement:
➢ The switch statement is used to select one operation from many operations.
The general form is,
switch(expression)
{
case label1:
block1 statement;
break;
case label2:
block2 statement;
break;
…….
default:
default block;
}
Execution:
statement-n;
• Where expression is an integer expression or a single character constants. Block1,Block2..etc,
are a group of statement or may be a single statements. There is no need to put braces around
the blocks.
• Label1,Label2…etc, are case labels and must be unique.
• The case labels may be integer constants or single character constants. The case labels should
end with the colon.
• The switch statement tests the value of the expression against the case labels. When a match is
found a block of statements associated with the case is executed.
• The break statement denoted the end of the case and causes an exits from the switch statement
and the control is transferred to the default case is optional.
• If no match is found the default block will be executed.
Ex:
class add
{
public static void main(String args[])
{
char choice=’-‘;
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 22
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
float a=4,b=3,c;
switch(choice)
{
case ‘+’:
c=a+b;
break;
case ‘–‘:
c=a-b;
break;
case ‘*’:
c=a*b;
break;
case ‘/’:
c=a/b;
break;
}
System.out.println (c);
}
2. DO…..WHILE LOOP
➢ It is an exit controls loop.
The general form is
do
{
Body of the loop;
}
while(condition);
Execution:
o The body of the loop is executed and then the condition is check.
o If the condition is true the body of the loop will be executed. otherwise the control is
terminated
o Even if the condition false at the begin the loop is executed for the first time
/*program*/
class sums
{
public static void main(String args[])
{
int sum,n=5,i;
sum=0;i=1;
do
{
sum=sum+i;
i++;
}
while(i<=n);
System.out.println (“the sum of first 5 numbers”+n+sum);
}
3. FOR LOOP:
It is entry control loop.
General Form:
Execution:
• The initialization of the control variable is done using the assignment statement.
• The value of the control variable is tested using the test condition.
• If the condition is true body of the will be executed.
• If the condition is false the body of the loop will not executed and the control is transferred to
the statement following the loop.
• The control variable is increment or decrement using the increment or decrement section and
the new value is tested against to the condition.
/*Fibonacci*/
class Fibonacci
{
public static void main(String args[])
{
int f0=0,f1=1,f2,n=5,i;
System.out.println (f0);
System.out.println(f1);
for(i=0;i<=n;i++)
{
f2=f0+f1;
System.out.println (f2);
f0=f1;
f1=f2;
}
for(i=0;i<3;i++)
{
for(j=0;j<3;++)
{
ans[i][j]=matrix[i][j]+matrix[i][j];
System.out.println(ans[i][j]);
}
System.out.println (“\n”); } }
Additional Features Of For Loop:
1) More than one variable can be initialized in the initialization section.
The variable must be separated by comma.
eg.
for(i=1;sum=0;i<=n;i++)
sum=sum+i;
2) More than one condition can be checked.
eg.
for(i=1;sum=0;i<=5&&sum<=10;i++)
sum=sum+i;
3) It is possible to use assignment statement in the initialization and increment section.
eg.
for(x=(m+n)/2;x>0;x=x/2)
4) It is possible to omit one on more section but the test condition must be stated.
eg.
for(i<=10)
{
System.out.println (“%d”,i);
i++;
}
5)It is possible to set time delay the loop.
eg.
for(j=1000;j>=0;j--)
GOTO Statement:
o It is branching statement and is used to transfer the control to any statement.
o It is a unconditional statement, since it is simply transfer the control without checking
any condition.
General format
goto label name
Forward Jump
➢ If the label statement is placed after the goto statement.
General format
goto label;
label: stat-x
➢ In the forward jump a set of statement are skipped and the control is transferred to label
statement.
/*program*/
class number
{
public static void main(String args[])
{
int number=4;
if(number<=5)
goto last;
else
{
System.out.println (“the number is not less than 5”);
}
last: System.out.println (“the number is less than 5”);
}
Backward Jump
➢ If the label statement is placed before the goto statement.
General format
label: stat-x
goto label;
➢ In the backward jump a set of statements repeatly executed. The statements are executed
infinite number of times. To terminate the infinite execution the user has check the condition.
/*program*/
class backward
{
public static void main(String args[])
{
read:int number=3;
if(number<=5)
System.out.println(“the number is less than 5”);
else
{
goto read;
}
}
TYPE CONVERSION :
➢ Type conversion is a process in which the data type is automatically converted into another
data type. The compiler does this automatic conversion at compile time.
➢ The data type to which the conversion happens is called the destination data type, and the data
type from which the conversion happens is called the source data type.
➢ If the source and destination data types are compatible, then automatic type conversion takes
place.
➢ For type conversion to take place, the destination data type must be larger than the source type.
In short, the below flow chart has to be followed.
➢ In type conversion, the source data type with a smaller size is converted into the
destination data type with a larger size.
➢ Before looking at an example for the type conversion type, let's see what happens when
incompatible data types are given.
public class Main {
public static void main(String[ ] args) {
int intType = 20;
// Short is of lower data type than int
short shortType = intType;
System.out.println("intType: "+intType);
System.out.println("shortType: "+shortType);
}
}
Run Code
Compile Time Error:
In the above case, short is of lower data type than int, hence a compile-time error occurs.
System.out.println("intType: "+intType);
System.out.println("floatType: "+floatType);
}
}
Output:
intType: 20
floatType: 20.0
TYPE CASTING:
➢ Type casting is a process in which the programmer manually converts one data type into
another data type. For this the casting operator (), the parenthesis is used.
➢ Unlike type conversion, the source data type must be larger than the destination type in type
casting. The below flow chart has to be followed for successful type casting.
➢ In type casting, the source data type with a larger size is converted into the destination
data type with a smaller size.
➢ In one of the examples covered in type conversion, you might recollect we encountered an
error while converting an int data type to short. Now, we will see how to solve that error by
using type casting.
Example
public class Main {
public static void main(String[] args) {
int intType = 20;
// Short is of lower data type than int
short shortType = (short)intType;
System.out.println("intType: "+intType);
System.out.println("shortType: "+shortType);
}
}
Output:
intType: 20
shortType: 20
ARRAYS:
➢ It is a collection of related data items and stored in the same data type.
➢ A particular value is indicated by writing a number called index number or subscript in
brackets after arrayname. e.g. salary[10]
types of arrays:
• One dimensional array.
• Two dimensional array.
• Multi dimensional array.
eg.
int number[15];
char name[10];
storage process:
number[0]=23;
number[1]=33;
number[2]=53;
number[3]=63;
number[4]=73;
char name[10];
we read “welldone” and it stored as follows,
name[0]=’w’;
name[1]=’e’;
name[2]=’l’;
name[3]=’l’;
name[4]=’’;
name[5]=’d’;
name[6]=’o’;
name[7]=’n’;
name[8]=’e’;
name[9]=’\0’;->null character.
/*read 5 number and print the number*/
class array
{
public static void main(String args[])
{
int a[2],i;
a[0]=9;
a[1]=8;
a[2]=7;
for(i=0;i<2;i++)
{
System.out.println(a[i]);
}
}
Creating an Array
• Arrays must be declared and created in computer memory.
• Creating of an array involves 3 steps:
• Declaring array
• Creating memory locations.
• Putting values into memory locations.
Declaration of Arrays:
Arrays may be declared into 2 forms.
Type arrayname[ ];
Type [ ] arrayname;
e.g. int number[ ];
float[ ] marks;
Creating of Arrays:
After declaring an array to create it in memory.
To create an array using new operator only.
Arrayname = new type[size];
e.g. number = new int[5];
average = new float[10];
To combine 2 steps:
Declaration and creation
Int number[] = new int[5];
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 31
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
eg.
int matrix[m][n];
m->rows;
n->columns;
the array can be declared by passing of values of numbers of rows and number of
columns as subscript values.
eg. column
rows
Initialization Arrays:
The values can also be initialized by enclosed with in braces.
eg.
int array[3][4]={{0,1,2,3},{4,5,6,7},{8,9,10,11}};
(or)
int array[3][4]={0,1,2,34,5,6,78,9,10,11};
Program:
1)/*To print the matrix elements*/
class array
{
public static void main(String args[])
{
int a[20][20],i;
a[0][0]=8;
a[0][1]=7;
a[1][0]=8;
a[1][1]=7;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
System.out.println(a[i][j]);
}
}
}
Variable size Arrays:
• Java treats multidimensional array as arrays of arrays.
• Declaration:
• Int x[][] = new int [3][];
• X[0]= new int[2];
• X[1]= new int[4];
• 2D array as having different lengths for each row.
X[0]=x[0][1];
X[1]=x[1][3];
X[2]=x[2][2];
Comment Statement
❖ It comprises a set of comment lines giving the name of the program, the author and other
details which the programmer would like to refer to at a later stage.
E.g.:
// this is a sample program
/* this is a java program */
Package statement:
❖ The first statement allowed in a java file is a package statement.
❖ This statement declares a package name and informs the compiler that the classes defined here
belong to this package.
E.g.: package student;
Import statement:
The next thing after a package statement may be a number of import statements. This is similar
to the #include statement in C.
E.g.: import student.test;
Interface Statements:
❖ It is like a class but includes a group of method declarations. It is used in implementing
multiple inheritances.
Class definitions
❖ These are the primary and essential elements of a java program.
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 34
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Method declaration:
➔ Methods are declared inside body of the class but immediately after the declaration of instance
variable.
Syntax:
type method name (parameter list)
{
method body;
}
Method declaration a basic parts:
➔ Name of the method (method name).
➔ Types of the value method return (type).
➔ List of parameter (parameters-list).
➔ Body of the method.
➔ Type -> type of value the method would return.
Eg: int
Eg: void->doesn’t return any value.
Method name->valid identifier
Parameter-list->it is enclosed in parameter.
List contain variable name &type variable in the list are seperated by commas.
Eg: (int m,float x,float y)
Body->operation to be performed on data.
Program:
class rectangle
{
int length;
int width;
void getdata(int x,int y)
{
length=x;
width=y;
}
int rectraea()
{
int area=length*width;
return(area);
}
}
Creating objects
Object:
➔ An object is essentially a block of memory that contain space to store all instance variable.
➔ Creating an object is also referred to as instantiating an object.
➔ Objects are created using new operator.
➔ New operator creates an object of the specified class &returns a reference to that object.
Eg:
rectangle rect1;
rect1=new rectangle();
class rectarea
{
public static void main(String args[])
{
int area1, area2;
rectangle rect1=new rectangle ();
rectangle rect2=new rectangle ();
rect1.length=15;
rect1.width=10;
area1=rect1.length*rect1.width;
rect2.getdata(20,12);
area2=rect2.rectarea();
System.out.println(+area1);
System.out.println(+area2);
}
}
OUTPUT:
area1=150
area2=290
CONSTRUCTORS:
➔ java supports a special type of method called a constructor, enables an object to initialize
itself when it is created.
➔ Constructor have the same name as the class itself.
➔ They don’t specify any return type not even void.
Program:
class rectangle
{
int l , w;
rectangle(int x,int y)
{
l = x;
w = y;
}
int rectarea()
{
return(l*w);
}}
class rectanglearea
{
public static void main(String args[])
{
rectangle rect1=new rectangle(15, 10);
int area1=rect1.rectarea();
System.out.println(“area1”+area1);
}}
int largest()
{
if (m>=n)
return(m);
else
return(n);
}
void display()
{
int large=largest();
System.out.println(“largest value=”+large);
}
}
class nestingtest
{
public static void main(String args[])
{
nesting nest=new nesting(50,40);
nest.display();
}
}
RECURSION:
Java supports recursion , Recursion means the process of defining something in terms of itself.
In java recursive is one of the attribute that allows a method to call itself.
A method that calls itself until a condition has to be satisfied is called a recursive method.
Ex:
import.java.io.*;
class factorial
{
int fact(int n)
{
int result;
if(n == 1)
return 1;
result = fact(n -1 ) * n;
return result;
}
}
class recursion
{
public static void main(String arg[])
{
factorial f = new factorial();
System.out.println(“factorial of 3 is +f.fact(3));
System.out.println(“factorial of 4 is +f.fact(4));
System.out.println(“factorial of 5 is +f.fact(5));
}}
STRINGS:
String manipulation is common part.
Strings represents a sequence of character.
To represent a sequence of characters by using a character array.
e.g.
char charArray[ ]=new char[4];
It is not enough to support some of operations.
So java is handle these situations more efficiently.
Strings are class objects & implements using 2 classes.
STRING AND STRINGBUFFER
Java string is an instantiated object of string class.
Java string is not a character array and is not NULL terminated.
It may declared & created as follows:
String StringName;
StringName = new String(“string”);
e.g.
String fname;
fname=new String(“Anil”);
Get length of String:
int m = fname.length();
Concatenated using (+) operator:
String fname = name1+name2;
String city1=”New”+”Delhi”;
String Arrays:
It can also create & use arrays contain Strings.
String itemarray[]=new String[3];
It will create an itemArray of size 3 to hold 3 string constants.
String Methods:
string class defines a no of methods.
s2=s1.toLowerCase;→Converts s1 to lowercase;
s2=s1.toUpperCase;→Converts s1 to uppercase;
s2=s1.replace(‘x’,’y’);→Replace all appearances of x with y.
s2=s1.trim()→Remove whitespaces at beginning and end.
S1.equals(s2);→Returns true if s1 is equal to s2;
S1.length();→Gives length of s1.
S1.CharAt(n)→Gives nth char of s1.
s1.CompareTo(s2)→s1 is compared to s2.
S1<s2→Negative.
S1>S2→Positive.
S1=S2→0.
S1.concat(S2)→Concatenates s1 & s2.
S1.subString(n)→Gives Substring starting from nth character.
S1.subString(n,m)→Gives Substring starting from nth char upto mth.
S1.indexOf(‘x’)→Gives position of first occurrence of ‘x’ in string S1.
Program:
class StringOrder
{
static String name[]={“Madras”,”Delhi”,”Mumbai”,”Calcutta”,”Bangalore”};
public static void main(String args[])
{
int size = name.length;
String temp=null;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(name[j].CompareTo(name[i])<0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}} }
for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}}}
StringBuffer Class:
StringBuffer is a peer class of string.
String creates Strings of fixed_length.
StringBuffer creates Strings of flexible length can be modified of both length & context..
It can insert characters & substrings in middle of a string or append another String to end.
StringBufferMethods:
S1.setCharAt(n,’x’)→Modifies nth char to x.
S1.append(S2)→Appends String s2 to s1 at end.
S1.insert(n,s2)→Inserts String s2 at position n of String S1.
S1.setLength(n)→Sets Length of String s1 to n.
Program:
class sm
{
public static void main(String args[])
{
StringBuffer str = new StringBuffer (“object Language”);
System.out.println(“original string:”+str);
System.out.println(“Length of String:”+str.length();
for(int i=0;i<str.length();i++)
{
int p=i+1;
System.out.println(“char at position:”+p+”is”+str.charAt(i));
}
UNIT – II
Inheritance : Basic concepts - Types of inheritance - Member access rules- Usage of this and
Super Keyword – Method Overloading – Method overriding - Abstract classes - Dynamic method
dispatch - Usage of final keyword. Packages: Definition-Access Protection – Importing Packages.
Interfaces : Definition–Implementation– Extending Interfaces. Exception Handling: try – catch -
throw – throws – finally – Built-in exceptions – Creating own Exception classes.
INHERITANCE:
Extending a class
➢ Java class can be reused in several ways .
➢ This is basically done by creating new classes, reusing the properties of existing ones.
➢ The mechanism of deriving a new class from an old one is called inheritance.
➢ The old class is known as the base class or super class or parent class and the new one is called
the sub class or derived class or chaild class.
➢ Inheritance may take different forms:
• Single inheritance(only one super class)
• Multiple inheritance (several super classes)
• Hierarchical inheritance(one super class,many sub class)
• Multilevel inheritance(Derived from a derived class)
➢ Java does not directly implement multiple inheritance.
➢ This concept is implemented using a secondary inheritance path in the form of interfaces.
Defining a subclass
Syntax :
class sub class name extends super class name
{
Variables declaration;
Methods declaration;
}
➢ This keyword extends signifies that the properties of the superclassname are extended to the
subclassname .
➢ The sub class will contain its own variables and methods as well those of the super class.
Syntax
class sub class name extends super class name
{
Variables declaration;
Methods declaration;
}
➢ This keyword extends signifies that the properties of the superclassname are extended to the
subclassname .
➢ The sub class will contain its own variables and methods as well those of the super class.
Program: single inheritance
class room
{
int length;
int breadth;
room(int x,int y)
{
length=x;
breadth=y;
}
int area()
{
return(length*breadth);
}
}
class bedroom extends room
{
int height;
bedroom(int x,int y,int z)
{
super(x,y)
height=z;
}
int volume()
{
return(length*breadth*height);
}
}
class inhertest
{
public static void main(String args[])
{
bedroom room1=new bedroom(14,12,10);
int area1=room.area();
int volume1=room1.volume();
System.out.prientln(“Area1=”+area1);
System.out.println(“Volume=”+Volume);
}
}
Subclass constructor
➢ A subclass constructor is used to construct the instance variable of both the subclass and the
superclass.
➢ The subclass constructor uses the keyword super to invoke the constructor method of the
superclass.
➢ The keyword super is used subject to the following conditions
1. super may only be used within a subclass constructor.
2. The cell to superclass constructor must appear as the first statement within the subclass
constructor.
3. The parameters in the super call must match the order and type of the instance variable
declared in the superclass.
MULTILEVEL INHERITANCE
➢ A common requirement in object-oriented programming is the use of derived class as a
superclass.
➢ Java supports this concept and uses it extensively in building its class library.
A
➢ The class A serves as a base class for the derived class B which in turn serves as a base
class for the derived class C.
➢ The chain ABC is known as inheritance path.
➢ A derived class with multilevel base class is declared as follows.
Syntax:
class A
{
………………..
…………………
}
class B extends A
{
…………………..
…………………..
}
class C extends B
{
……………….
……………..
}
Example program:
import java.io.*;
class students
{
int rollno;
String name;
void getnumber( int r, String sn)
{
rollno = r;
name= sn;
}
void putnumber( )
{
System.out.println(“Rollno + rollno);
System.out.println(“Name”+name);
}
}
class mark extends students
{
float mark1,mark2,mark3;
void getmark(float m1,float m2, float m3)
{
mark1=m1;
mark2=m2;
mark3=m3;
}
void putmarks( )
{
System.out.println(“Mark1” +mark1);
System.out.println(“Mark2” +mark2);
System.out.println(“Mark3” +mark3);
}
}
class result extends mark
{
float total,avg;
void display( )
{
total = mark1+mar2+mar3;
avg = total/3;
putnumbers( );
putmarks();
System.out.println(“Total” +total);
System.out.println(“Average” +avg);
}
}
class multi
{
public static void main(String args[ ])
{
result r1 = new result()
r1.getnumber(34,”Nareshkumar”);
r1.getmarks(92.0f,98.0f,96.0f);
r1.display();
}
}
Hierarchical inheritance
➢ Hierarchy where certain features of one level are shared by many other below the level.
➢ A hierarchical classification of accounts in a commercial.
Syntax:
class A
{
………………..
…………………
}
class B extends A
{
…………………..
…………………..
}
class C extends A
{
……………….
……………..
}
METHOD OVERLOADING:
➔ To create methods have the same name,but different parameter lists and different definitions.
➔ This is called as method overloading.
➔ Method overloading is used, when objects are required to perform similar tasks but different
input parameters.
➔ Java matches up method name first and number & type of parameter ->called as
polymorphism.
➔ To create an overloading method , provide server different method definitions, all with same
name, but different parameter lists.
Eg program:
class room
{
float l;
float b;
room(float x,float y)
{
l=x;
b=y;
}
room(float x)
{
length=b=x;
}
int area()
{
return(l*b);
}
}
class rectangle
{
public static void main(String args[])
{
room r1=new room(25.0,15.0);
room r2=new room(20.0);
int area1=r1.area();
int area2=r2.area();
System.out.println(+area1);
System.out.println(+area2);
}
}
OVERRIDING METHODS
➢ In overriding methods defining a methods in a subclass that the same name, same arguments
and same return type as a methods in the subclass.
➢ Methods is called,the method defined in the subclass is invoked and executed instead of the
one in the superclass this is known as overriding.
Program : lllustration of method overriding
import java.io.*;
class super
{
int x;
super(int x)
{
this.x=x;
}
void display()
{
System.out.println(“Super x=”+x);
}
class sub extends super
{
int y;
sub(int x,int y)
{
super(x);
this.y=y;
}
void display()
{
System.out.println(“super x=”+x);
System.out.println(“sub y=”+y);
}
}
class OverridingTest
{
public static void main(String args[])
s1.display();
}
}
FINAL VARIABLES:
➢ All methods and variables can be overridden by default in subclasses, if we wish to prevent the
subclasses from overrding the members of the superclasses,we can declare them as final using
the keyword final as amodifier.
Syntax:
Final type symbolicname = variable;
Example:
final int SIZE=100;
final void showstatus();
➢ The functionality defined in this method will be altered in any way.
➢ The value of the final variable can never be changed.
FINAL CLASSES:
➢ To prevent a class being further subclasses for security.
➢ A class that cannot be subclassed is called a final class.
➢ This achieved in java using final keyword as follows,
final ClassA class{…………….}
final classB class extends someclass{………………}
Syntax:
final class classname
{
Body of the class
}
The reverse format in sub class is
final class sub_classname extends super_classname
{
Body of the subclass
}
➢ Declaring a class final prevents any unwanted extension to the class.
FINAL METHODS:
All methods and variables can be overridden by default in subclass. If we wish to
prevent the subclass from overriding the members of the superclass, we can declare
them as final using the keyword final.
Final member cannot be altered.
Ex:
final int size=100;
final void show()
{
---------
}
Finalize( ) Methods
➢ A Constructor method is used to initialize sn object when it is declared. This process is known
as initialization.
➢ Java supports a concept called finalization, which is just opposite to initialization.
➢ Java run-time is an automatic garbage collecting system.
➢ It automatically frees up the memory resources used by the object.
➢ But object may hold other non-object resources such as file descriptors or window system
fonts.
➢ The garbage collector cannot free these resources. in order to free these resources we must use
finalizer method.
➢ The finalizer method is simply finalize() can be added to any class.
Ex:
protected void finalize( )
{
// finalization code
}
→ Use of Final keyword:
1. Using final to prevent overriding.
2. Using final to prevent inheritance.
super Keyword
➢ A reserved keyword used to call the base class method or variable is known as
a super keyword.
➢ We cannot use the super keyword as an identifier.
➢ The super keyword is not only used to refer to the base class instance but also static members
too.
super( ) Constructor
➢ The super( ) is mainly used for invoking base class member functions and constructors.
➢ Let's take an example of both the super keyword and super() to understand how they work.
SuperExample1.java
// import required classes and packages
package javaTpoint.MicrosoftJava;
// create Animal class which is base class of Animal
class Animal{
// data member of Animal class
String color = "white";
}
// create child class of Animal
class Cat extends Animal{
//default constructor
Cat( )
{
// data members of the Cat class
String color = "Brown";
System.out.println("The cat is of color "+super.color);
System.out.println("The cat is of color "+color);
}
}
// create child class for Car
class SuperExample1 extendsCat
{
// default constructor
SuperExample1()
{
// calling base class constructor
super();
System.out.println("The eyes of the cat is blue.");
}
// main() method start
publicstaticvoid main(String[] args)
{
// call default constructor of the SuperExample1
new SuperExample1( );
System.out.println("Inside Main"); } }
Output:
The cat is of color white
The cat is of color Brown
The eyes of the cat is blue.
Inside Main
➢ In the main() method, we have made a statement new SuperExample1( ). It calls the
constructor of the SuperExample1 class.
➢ Inside the constructor, we have made statement super() which calls the constructor of its
parent class, i.e., Cat. In the constructor, we have made three statements:
1. Initialize color with value 'Brown'.
2. Print parent class data member.
3. Print current class data member.
➢ When the second statement executes, the flow of the program jumps to Animal class to access
the value of its data members. After accessing it, the flow comes back to the Cat class
constructor and prints it. After that, the last statement executes and prints the value of the
variables of the current class.
➢ After execution of the last statement of the Cat class, the flow comes back to the constructor of
class SuperExample1 and executes the remaining statements.
➢ After completing the execution of the SuperExample1( ), the flow comes back to the main()
method and executes the remaining statements.
➢ Note: In order to use the super(), we have to make sure that it should be the first statement in
the constructor of a class. We can use it to refer only to the parent class constructor.
this keyword
➢ It is a reserved keyword in Java that is used to refer to the current class object.
➢ It is a reference variable through which the method is called. Other uses of this keyword are:
o We can use it to refer current class instance variable.
o We can use it to invoke the current class method (implicitly).
o We can pass it as an argument in the method and constructor calls.
o We can also use it for returning the current class instance from the method.
this( ) Constructor
➢ The constructor is used to call one constructor from the other of the same class.
➢ Let's take an example of both this keyword and this( ) to understand how they work.
ThisExample1.java
// import required classes and packages
package javaTpoint.MicrosoftJava;
// create ThisExample1 class to understand the working of this() and this
class ThisExample1 {
// initialize instance and static variable
int x = 5;
staticinty = 10;
// default constructor of class ThisExample1
ThisExample1()
{
// invoking current class constructor
this(5);
System.out.println("We are insie of the default constructor.");
System.out.println("The value of x = "+x);
}
ThisExample1(int x)
{
this.x = x; // override value of the current class instance variable
System.out.println("We are inside of the parameterized constructor.");
System.out.println("The value of y = "+y);
}
publicstaticvoid main(String[] args)
{
// invoking constructor of the current class
new ThisExample1();
System.out.println("Inside Main");
}
}
Output:
We are inside of the parameterized constructor.
The value of y = 10
We are inside of the default constructor.
The value of x = 5
Inside main
The current instance of the class is represented The current instance of the parent class is
by this keyword. represented by the super keyword.
In order to call the default constructor of the In order to call the default constructor of the
current class, we can use this keyword. parent class, we can use the super keyword.
It can be referred to from a static context. It It can't be referred to from a static context. It
means it can be invoked from the static context. means it cannot be invoked from a static context.
We can use it to access only the current class We can use it to access the data members and
data members and member functions. member functions of the parent class.
The this() constructor refers to the current class The super() constructor refers immediate parent
object. class object.
It is used for invoking the current class method. It is used for invoking parent class methods.
It can be used anywhere in the parameterized It is always the first line in the child class
constructor. constructor.
It is used for invoking a super-class version of an It is used for invoking a super-class version of an
overridden method. overridden method.
Example program
import java.io.*;
abstract class test
{
int i,j;
test( int I, int j)
{
this.i=I;
this.j=j;
}
void calc()
{
}
}
class sum extents test
{
sum(int i, int j)
{
super( I,j);
}
void calc( )
{
System.out.println(i+j);
}
}
class diff extents test
{
diff( int i, int j)
{
super( i ,j);
}
void calc()
{
System.out.println(i-j);
}}
class abstractprogram
{
public static void main(String args[])
{
test s1 = new sum(3,7);
s1.calc( );
s1=new diff(30,10);
s1.calc( );
}}
Upcasting :
➢ It is a technique in which a superclass reference variable refers to the object of the subclass.
Example :
class Animal{}
class Dog extends Animal{}
Copy
Animal a=new Dog();//upcasting
Copy
➢ In the above example, we've created two classes, named Animal(superclass) & Dog(subclass).
While creating the object 'a', we've taken the reference variable of the parent class(Animal),
and the object created is of child class(Dog).
Example to demonstrate the use of Dynamic method dispatch :
➢ In the below code, we've created two classes: Phone & SmartPhone.
➢ The Phone is the parent class and the SmartPhone is the child class.
➢ The method on() of the parent class is overridden inside the child class.
➢ Inside the main() method, we've created an object obj of the Smartphone() class by taking the
reference of the Phone() class.
➢ When obj.on() will be executed, it will call the on() method of the SmartPhone() class
because the reference variable obj is pointing towards the object of class SmartPhone().
class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
Two types:
1) java API packages
2 ) user defined packages
1) Java API packages:
• Java API ->a large no of classes grouped into different packages.
• A large no of classes grouped into different package according to functionality.
Java.lang:
• Language support classes.
• java compiler itself uses and therefore they are automatically imported.
• Includes->primitive type, strings, math function, threads and exceptions.
Java.util:
• Language utility classes such as vectors, hash tables, random numbers, data etc.
Java.io:
• i/o support classes
• provide facilities for input & output of data
Java.awt:
• set of classes for implementing graphical user interface.
• include classes for windows, buttons, list, menu & soon.
java.net:
• classes for networking
• include classes for communicating with local computers as well as internet servers
Java.applets:
• classes for creating & implementing applets.
Ex:
package firstpackage;
public class first class
{
body of class
• Firstpackage is a package name.
• Class firstclass is a part of the package.
• To save a file called as firstclass.java & located in directory named firstpackage.
• Cource file is compiled, create a class file & store in same directory.
Steps:
1. declare package at beginning of a file.
package packagename;
2. define class in package & declare it public.
3.Create a subdirectory under directory where main source files are stroed.
4.Store listing as classname.java file in subdirectory created.
5.Compile file.creates.class file in subdirectory.
• java supports concept of package hierarchy.
• this is done by separated by dots.
package firstpackage.secondpackage;
Accessing a package:
• Java system package can be accessed either using a fully qualified class name or using a
shortcut through import statement.
• Import statement can be used to search a list of package for a particular class.
Syntax:
1) import package[.package2][.package3].classname;
• package is name of top level package.
• package2 is name of the package inside package1.
• classname is specified.
• Statement end with a semicolon(:)
Eg:
import firstpackage.secondpackage.myclass;
Myclass can be directory accessed using class or its objects.
2) import packagename.*;
Packagename may denote a single package or hierarchy of packages.
• star(*)->compiler should search entire package hierarchy.
• it can access all classes contained in above package directly.
Using a package:
Eg:
package package1;
public class classA
{
public void displayA()
{
System.out.println(‘’classA’’)’
}
}
• Class.java is stored in the subdirectory package1.after compiler, classA.class will be stored in
same subdirectory.
import package1.classA;
class packagetest1
{
public static void main(String args[])
{
classA objA=new classA90;
objA.displayA();
}
}
• Imports class classA from package package.
• source file will be packagetest.java & compiled in the package1.
• During compiler of packagetest.java compiler checks for classA class in package1.
• During run of packagetest1, it looks the file packagetest1.class & loads using class loader.
• Interpreter knows it also needs the code in file classA.class & loads it as well.
Eg:
package package2;
public class classB
{
protected int m=10;
public void display()
{
System.out.println(‘’classB’’)
System.out.println(‘’m=’’’+m);
}
}
• Sourcefile & compiled file of this package are located in subdirectory,package2.
• Importing classes from other packages.
import package1.classa;
import package2.*;
class package test2
{
public static void main(string args[])
{
classA objA=new classA();
classB objB=new classB();
objA.displayA();
objB.displayB();
}
}
Save-package test2.java
o/p:
class A
class B
m=10
Hiding classes:
• ->Import a package using (*),all public classes are imported.
• ->To prefer to ‘’not import’’ certain classes.
• ->To hide these classes from accessing from outside of the package.
• ->Such classes should be declared ‘’not public’’.
Eg:
package p1;
{
body of x;
}
class y
{
body of y;
}
• Y is not declared public is hidden from outside of the package p1.
• This class can be used by other classes in same package.
• Import package p1 contain classes X & Y.
Ex:
import p1.*;
X objectX; -> ok, available.
Y objectY; ->not ok, not available.
Javac ->can produce error message because Y is not declared public.
Static import:
• ->Static import is another language.
• ->Static import is similar to import.
• ->Import ->to import static member from classes.
syntax:
import static package-name.subpackage-name.classname.staticmember-name.
(or)
import static package-name.subpackage-name.class-name.*;
Eg:
double area-of-circle=math.pi*r*r;
• Pi is static member of class, math.
• Pi is used with qualified class name math.
To use static member in an interface, to use it in a class, then to implement interface in the class.
public interface salary-increment
{
public static final double manager=0.5;
public static final double clerk=0.25;
}
Salary-increment is available in employee package.
To import interface using static import statement.
Import static employee.employee-details, salary-increment;
class salary-like
{
public static void main(String argsp[])
{
double MS=manager * MCS;
double CS=clerk * CCS;
}
}
➔ To use static member in code without qualifying class name or interface name.
➔ Static import ->eliminates redundancy of using qualified class name with static member name
& increase reliability.
import static java.lang.math.*;
public class methop
{
public void circle(double r)
{
double area=pi*r*r;
System.out.println(+area);
}
Access protection:
The three access specifiers private,public and protected.
Private->cannot be seen out side of the class.
Public->can be accessed from anywhere.
Protected->if you want to allow an element to be seen outside your current package.
Visibility of class members Private Protected public
Same class Yes Yes Yes
Same package subclass No Yes Yes
Same package non-subclass No Yes Yes
Different package subclass No Yes Yes
Different package non-subclass No Yes Yes
INTERFACE:
Defining interfaces:
• An interface is a kind of a class.
• Interface contain method & variable but difference.
• To define only abstract method & final fields.
• Interface don’t specify any code to implement these method & data fields contain only
constants.
Syntax:
interface interfacename
{
variable declaration;
method declaration;
}
inteface is a keyword
Variable declaration:
➔ Static final type variablename=value;
➔ All variable are declared as constant.
➔ Method declaration:
➔ Method declaration will contain only a list of method without any body statement.
Ex:
return-type mathodname1(parameter-list);
{
static final int code =1001;
static final string name=’’fan’’;
void display();
}
Extending interface:
• Interfaces can also be extended.
• Interface can be subinterfaced from other interfaces.
• The new subinterface will inherit all the method of super of superinterface.
Syntax:
interface name2 extends name1
{
Body of name2;
}
Ex:
interface item constants
{
int code=1001;
String name=’’fan’’;
}
interface item extends itemconstants
{
void display();
}
interface item contants
int code=1001;
String=’’fan’’;
}
interface item mathods
{
void display();
}
area=rect;
System.out.println(+area.compute(10,20));
area=cir;
System.out.println(+area.compute(10,0));
}
}
OUTPUT:
Area of rectangle of rectangle=200
Area of circle=314
Accessing interface variables:
• interface can be used to declare set of contant -> can be used in different classes
• interface don’t contain method.
• constant value will be available to any class that implement interface.
• value can be used in any method,as part of any variable declaration,or anywhere can use final
value.
Ex:
class student
{
int rno;
void getno(int n)
{
rno=n;
}
void putno()
{
System.out.println(+rno);
}
}
class test extend student student
{
float p1,p2;
void getmarks(float m1,float m2)
{
p1=m1;
p2=m2;
}
void putmarks()
{
System.out.println(“marks’’);
System.out.println(+p1);
System.out.println(+p2);
}
}
interface sports
{
float sportwt=6.0f;
void putwt()
}
class res extends test implement sports
{
float tot;
public void putwt()
{
System.out.println(+sportwt);
}
void dis()
{
tot=p1+p2+sportwt;
putno();
putmarks();
putwt();
System.out.println(+tot);
}
}
class hybrid
{
public static void main(String args[])
{
res s1=new res();
s1.getno(1234);
s1.getmarks(12.5f,33.0f);
s1.dis();
}
}
OUTPUT:
rno=1234
p1=12.5
p2=33
sportwt=6
tot=66.5
EXCEPTIONS:
➢ An exception is a condition that is caused by a run-time error in the program.
➢ When the java interpreter encounters an error as dividing an integer by zero, it creates an exception
object and throws it that is informs us that an error has occurred.
➢ If the exception object is not caught and handled properly, the interpreter will display an error
message.
➢ Should try to catch the exception object thrown by the error condition and then display an
appropriate message for talking corrective actions.
➢ The error handling code basically consist of two segments, one to detect errors to throw exception
and the other to catch exception and to take appropriate actions.
Build in exception:
There are 2 types of build in exception available in java.
1)cheked. 2)unchecked.
Checked:
They need not be included in any throws list
Unchecked;
They need not be included in any throws list
The complie time error is the result
Checked
Exception type Cause of Exception
ArithmeticicException. Caused by math error such as division by zero.
Syntax:
try
{
Statement;
}
catch(exception-type1 e)
{
Statement;
}
catch(exception-type2 e)
{
Statement;
}
catch(exception-typeN e)
{
Statements;
}
……………………..
……………………..
➢ Catch statements ends with a semicolon.
Example:
class e4
{
public static void main(String args[])
{
int a[] = {5,10};
int b =5;
try
{
int x=a[2]/b-a[1];
}
catch (Arithmetic exception e)
{
System.out.println (“division by zero”);
}
catch (ArrayIndexoutOfBoundsException e)
{
System.out.println (“array index error”);
}
catch (arraystoreexception e)
{
System.out.println (“arraystoreexception”);
}
int y=a[1]/a[0];
System.out.println (“y=”+y);
}
}
Output:
➢ Array index error
➢ Y=2
➢ Array element a[2] does not exist because array is defined on;y two elements a[0]and
a[1].
➢ So index 2 is outside array boundary causing the block
➢ Catch (ArrayIndexOutOfBoundsException e) to catch and handle error.
➢ Remaining catch blocks are skipped.
Throw:
➢ It is used to throw our own exception.
➢ This is done by using throw keyword.
General Format:
throw new throwableinstance;
program:
class demo
{
public static void main(String args[])
{
int x=5,y=1000;
try
{
float z=x/y;
if(z<0.01)
{
throw new Exception("number is small"); }
}
catch(Exception e)
{
System.out.println("caught"+e);
}
}
}
E:\java>java demo
caught java.lang.Exception: number is small
SECOND METHOD
try
{
………………………..
……………………….
}
catch(……………..)
{
……………………
……………………….
}
catch(……………….)
{
……………………………..
……………………………
}
finally
{
…………………………..
……………………………
}
➢ Finally block is defined,it is compulsory to executed.
Example
finally
{
int y = a[1]/a[0];
System.out.println(“y=”+y);
}
Program:
class finaldemo
{
public static void main(String args[])
{
int a=5;
try
{
int x=a/0;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexoutOfBoundsException");
}
finally
{
int y=10/2;
System.out.println("y="+y);
}
}}
o/p:
E:\java>javac finaldemo.java
E:\java>java finaldemo
y=5
Method Description
Throwable fillInStackTrace( ) Returns a Throwable object that contains a completed stack trace.
This object can Be rethrown.
Throwable getCause( ) Returns the exception that underlies the current exception.
If there is no underlying exception, null is returned.
String getLocalizedMessage( ) Returns a localized description of the exception.
String getMessage( ) Returns a description of the exception.
void printStackTrace( ) Displays the stack trace.
void printStackTrace(PrintStream stream) Sends the stack trace to the specified stream.
void printStackTrace(PrintWriter stream) Sends the stack trace to the specified stream.
void setStackTrace(StackTraceElement elements[ ]) Sets the stack trace to the elements passed
in elements. This method is for specialized
applications, not normal use.
String toString( ) Returns a String object containing a description of the
exception. This methodcalled by println( ) when outputting a
Throwable object.
To throw our own exceptions by using throw keyword.
SYNTAX:
Throw new throwable_subclass
EXAMPLE:
throw new ArithmeticException ();
throw new NumberFormatException ();
import.java.lang.exception
class myexception extends exception
{
myexception (string message)
{
super (message);
}
}
class testmyexception
{
public static void main (strings args[])
{
int x=5,y=1000;
try
{
float z= (float) x/ (float) y;
if (z<0.01)
{
throw new myexception (“Number is to small”);
}
}
catch (my exception e)
{
System.out.println (“Caught my exception”);
System.out.println (e.message ());
}
finally( )
{
System.out.println (“I am always here”);
}
}
}
Output:
Caught my exception
Number is too small
I am always here
The object e which contains the error message “Number is too small” is caught by the catch block
which then displays the message using the getmessage() method.
UNIT – III
Multithreaded Programming : Thread Class – Runnable interface – Synchronization – Using
synchronized methods – Using synchronized statement-Interthread Communication – Deadlock.
I/O Streams: Concepts of streams- Stream classes -Byte and Character stream -Reading console Input
and Writing Console output – File Handling.
MULTITHREADED PROGRAMMING
• Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and very much platform dependentant.
Thread class:
➢ Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)
Commonly used methods of Thread class:
Thread Methods:
Public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread
object.
Public void run()If this Thread object was instantiated using a separate Runnable target, the run()
method is invoked on that Runnable object.
SYNCHRONIZATION:
Why use Synchronization?
The synchronization is mainly used to
1. To prevent thread interference.
2. To prevent consistency problem.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.
Thread Synchronization
➢ There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
➢ Mutual Exclusive helps keep threads from interfering with one another while sharing data. It
can be achieved by using the following three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization
Concept of Lock in Java
➢ Synchronization is built around an internal entity known as the lock or monitor. Every object
has a lock associated with it.
➢ By convention, a thread that needs consistent access to an object's fields has to acquire the
object's lock before accessing them, and then release the lock when it's done with them.
➢ From Java 5 the package java.util.concurrent.locks contains several lock implementations.
Understanding the problem without Synchronization
In this example, there is no synchronization, so output is inconsistent. Let's see the example:
TestSynchronization1.java
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500
SYNCHRONIZED METHOD
➢ If you declare any method as synchronized, it is known as synchronized method.
➢ Synchronized method is used to lock an object for any shared resource.
➢ When a thread invokes a synchronized method, it automatically acquires the lock for that
object and releases it when the thread completes its task.
TestSynchronization2.java
//example of java synchronized method
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
public class TestSynchronization2{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 82
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
200
300
400
500
Example of synchronized method by using annonymous class
➢ In this program, we have created the two threads by using the anonymous class, so less coding
is required.
TestSynchronization3.java
//Program of synchronized method by using annonymous class
class Table{
synchronized void printTable(int n){//synchronized method
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
public class TestSynchronization3{
public static void main(String args[]){
final Table obj = new Table();//only one object
Thread t1=new Thread(){
public void run(){
obj.printTable(5);
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
INTER-THREAD COMMUNICATION
➢ Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
➢ Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running
in its critical section and another thread is allowed to enter (or lock) in the same critical section
to be executed.It is implemented by following methods of Object class:
✓ wait()
✓ notify()
✓ notifyAll()
1) wait() method
✓ The wait() method causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.
✓ The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
2) notify() method
✓ The notify() method wakes up a single thread that is waiting on this object's monitor. If any
threads are waiting on this object, one of them is chosen to be awakened.
✓ The choice is arbitrary and occurs at the discretion of the implementation.
Syntax:
1. public final void notify()
3) notifyAll() method
✓ Wakes up all threads that are waiting on this object's monitor.
Syntax:
1. public final void notifyAll()
The wait() method releases the lock. The sleep() method doesn't release the lock.
It should be notified by notify() or notifyAll() After the specified amount of time, sleep is
methods completed.
Example of Inter Thread Communication
Let's see the simple example of inter thread communication.
Test.java
class Customer
{
int amount=10000;
synchronized void withdraw(int amount){
System.out.println("going to withdraw...");
if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount){
System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}}
class Test{
public static void main(String args[]){
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 85
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
}}
Output:
going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
DEADLOCK :
➢ Deadlock in Java is a part of multithreading. Deadlock can occur in a situation when a thread is
waiting for an object lock, that is acquired by another thread and second thread is waiting for
an object lock that is acquired by first thread.
➢ Since, both threads are waiting for each other to release the lock, the condition is called
deadlock.
Example :
TestDeadlockExample1.java
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "ratan jaiswal";
final String resource2 = "vimal jaiswal";
// t1 tries to lock resource1 then resource2
Thread t1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
DeadlockSolved.java
public class DeadlockSolved {
public static void main(String ar[]) {
DeadlockSolved test = new DeadlockSolved();
final resource1 a = test.new resource1();
final resource2 b = test.new resource2();
// Thread-1
Runnable b1 = new Runnable() {
public void run() {
synchronized (b) {
try {
/* Adding delay so that both threads can start trying to lock resources */
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Thread-1 have resource1 but need resource2 also
synchronized (a) {
3. Using Thread Join: A deadlock usually happens when one thread is waiting for the other to
finish. In this case, we can use join with a maximum time that a thread will take.
Java.io package provides classes for system input and output through files, network streams, memory
buffers, etc.
Some input-output stream will be initialized automatically by the JVM and these streams are available
in System class as in, out, and err variable.
➢ In reference refers to the default input device, i.e. keyboard.
➢ Out and err refers to the default output device, i.e. console.
Stream Classes:
A stream can be defined as a sequence of data. There are two kinds of Streams
➢ Input Stream Classes
➢ Output Stream Classes
Input Streams: Input streams are used to read the data from various input devices like keyboard, file,
network, etc.
Output Streams: Output streams are used to write the data to various output devices like monitor,
file, network, etc.
There are two types of streams based on data:
➢ Byte Stream: used to read or write byte data.
➢ Character Stream: used to read or write character data.
Byte Streams:
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream. Following is an example which makes use of these two
classes to copy an input file into an output file
Example
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
package com.javatpoint;
import java.io.*;
public class DataStreamExample
{
public static void main(String args[])throws Exception
{
FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");
FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");
ByteArrayOutputStream bout=new ByteArrayOutputStream();
bout.write(65);
bout.writeTo(fout1);
bout.writeTo(fout2);
bout.flush();
bout.close();//has no effect
System.out.println("Success...");
}
}
Output:
Success...
f1.txt:
A
f2.txt:
A
Output:
Hello Intellipaat
Example2:
import java.io.*;
public class ReadFileDemo
{
public static void main(String[] args)
{
BufferedReader br = null;
BufferedReader br2 = null;
try
{
br = new BufferedReader(new FileReader(“B:\\myfile.txt”));
String contentLine = br.readLine();
while (contentLine != null)
{
System.out.println(contentLine);
contentLine = br.readLine();}
}
catch (IOException ioe)
{
ioe.printStackTrace();}
}
Output:
Now you know how to create & read
Output:
Enter the password: //input will not visible in the console
Entered password: passphrase
1.3. Read Input with reader()
Console console = System.console();
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
}
Reader consoleReader = console.reader();
Scanner scanner = new Scanner(consoleReader);
System.out.println("Enter age:");
int age = scanner.nextInt();
System.out.println("Entered age: " + age);
scanner.close();
Output:
Enter age:
12
Entered age: 12
while((r=fis.read())!=-1)
{
System.out.print((char)r); //prints the content of the file
} }
catch(Exception e)
{
e.printStackTrace();
} }
}
Output:
Closing a file:
package com.tutorialspoint;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStreamDemo
{
public static void main(String[] args) throws IOException
{
FileOutputStream fos = null;
try
{
// create new file output stream
fos = new FileOutputStream("C://text.txt");
// close stream
fos.close();
// try to write into underlying stream
fos.write(65);
fos.flush();
fos.close();
}
catch(Exception ex)
{
// if any error occurs
System.out.print("IOException: File output stream is closed");
}
finally
{
// releases all system resources from the streams
if(fos!=null)
fos.close();
}}
}
The two important streams are FileInputStream and FileOutputStream, which would be
discussed in this tutorial.
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the
keyword new and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the file −
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows −
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Once you have InputStream object in hand, then there is a list of helper methods which can be used to
read to stream or to do other operations on the stream.
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try{
if (fileInputStream != null)
{
fileInputStream.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return fileInputStream;
}
public static void main(String[] args)
{
ExceptionExample instance1 = new ExceptionExample();
instance1.testMethod1();
}
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally{
try{
fos.close();
fis.close();
}
catch(IOException e){}
}
}
RANDOM ACCESS FILE:
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving the
cursor we do the read write operations. If end-of-file is reached before the desired number of byte has
been read than EOFException is thrown. It is a type of IOException.
Constructor
Example:
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample
{
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args)
{
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
}
catch (IOException e)
{
e.printStackTrace();
} }
private static byte[] readFromFile(String filePath, int position, int size) throws IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position) throws IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
UNIT – IV
AWT Controls : The AWT class hierarchy – user interface components – Labels – Button
Text Components - Check Box - Check Box Group - Choice -List Box - Panels – Scroll Pane - Menu -
Scroll Bar. Working with Frame class - Colour - Fonts and layout managers. Event Handling :
Events-Event sources – Event Listeners -Event Delegation Model (EDM) – Handling Mouse and
Keyboard Events - Adapter classes – Inner classes.
Components
➢ All the elements like the button, text fields, scroll bars, etc. are called components. In Java
AWT, there are classes for each component as shown in above diagram.
➢ In order to place every component in a particular position on a screen, we need to add them to
a container.
Ex. Button, TextField, TextArea
Container
➢ The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.
➢ It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
Window
➢ The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window. We need to create an instance of Window class to
create this container.
Panel
➢ The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.
Frame
➢ The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application.
Control Fundamentals:
The AWT supports the following types of controls:
Labels
Push
buttons
Check
boxes
Choice lists
Lists
Scroll bars
Text
Editing
➢ These controls are subclasses of Component Adding and Removing Controls: To include a
control in a window, you must add it to the window. To do this, you must first create an
instance of the desired control and then add it toa window by calling add(), which is defined by
Container. The General form is:
Component add(Component compObj)
➢ Here, compObj is an instance of the control that you want to add. A reference to compObj
is returned.
➢ Sometimes you will want to remove a control from a window when the control is no
longer needed. To do this, call remove( ). This method is also defined by Container.
Here isone of its forms:
void remove(Component obj)
➢ Here, obj is a reference to the control you want to remove. You can remove all controls by
calling removeAll( ).
The HeadlessException:
➢ Most of the AWT controls have constructors that can throw a HeadlessException when
an attempt is made to instantiate a GUI component in a non-interactive environment
(such as one in which no display, mouse, or keyboard is present).
Labels:
➢ The easiest control to use is a label. A label contains a string and is an object of type Label.
Labels are passive controls that do not support any interaction with the user.
Creating Label : Label l = new Label(String);
Label Constructors:
1. Label() throws HeadlessException: It creates a blank label.
2. Label(String str) throws HeadlessException: It creates a label that contains the string
specified by str.
3. Label(String str, int how): It creates a label that contains the string specified by str
using the alignment specified by how. The value of how must be one of these three
constants: Label.LEFT, Label.RIGHT, Label.CENTER.
Label Methods:
1. void setText(String str): It is used to set or change the text in a label by using the
setText() method. Here, str specifies the new label.
2. String getText(): It is used to obtain the current label by calling getText() method.
Here, the current label is returned.
3. void setAlignment(int how): It is used to set the alignment of the string within the
label by calling setAlignment() method. Here, how is one of the alignment constants?
4. int getAlignment(): It is used to obtain the current alignment, getAlignment() is called.
Example :
import java.awt.*;
import java.applet.*;
/*
<applet code = "LabelDemo" width=300 height=200>
</applet>
*/
public class LabelDemo extends Applet
{
public void init ( )
{
Label one = new Label ("One");
Label two = new Label ("Two");
Label three = new Label ("Three");
add (one);
add (two);
add (three);
}
}
Output:
➢ Here, you will get a response when the user will press ENTER.
AWT TextArea Control
➢ Sometimes one line of text input isn’t enough for a given task. To handle these situations, the
AWT includes an easy multiline editor called TextArea.
Creating TextArea : TextArea ta = new TextArea();
TextArea Constructor
1. TextArea() throws HeadlessException: It creates a default textarea.
2. TextArea(int numLines, int numChars) throws HeadlessException: It creates a text
area that is numChars characters wide. Here, numLines specifies the height, in lines of
the text area.
3. TextArea(String str) throws HeadlessException: It initializes the text area with the
string contained in str.
winVista.addItemListener (this);
solaris.addItemListener (this);
mac.addItemListener (this);
}
public void itemStateChanged (ItemEvent ie)
{
repaint ();
}
// Display current state of the check boxes.
public void paint (Graphics g)
{
msg = "Current state: ";
g.drawString (msg, 6, 80);
msg = " Windows XP: " + winXP.getState ();
g.drawString (msg, 6, 100);
msg = " Windows Vista: " + winVista.getState ();
g.drawString (msg, 6, 120);
msg = " Solaris: " + solaris.getState ();
g.drawString (msg, 6, 140);
msg = " Mac OS: " + mac.getState ();
g.drawString (msg, 6, 160);
}
}
Output:
CheckboxGroup Methods
1. Checkbox getSelectedCheckbox(): You can determine which checkbox in a group is
currently selected by calling getSelectedCheckbox().
2. void setSelectedCheckbox(Checkbox which): You can set a checkbox by calling
setSelectedCheckbox(). Here, is the checkbox that you simply want to be selected. The
previously selected checkbox is going to be turned off.
Example :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="CBGroup" width=250 height=200> </applet> */
public class RadiobuttonDemo extends Applet implements ItemListener
{
String msg = "";
Checkbox winXP, winVista, solaris, mac;
CheckboxGroup cbg;
public void init ()
{
cbg = new CheckboxGroup ();
winXP = new Checkbox ("Windows XP", cbg, true);
winVista = new Checkbox ("Windows Vista", cbg, false);
solaris = new Checkbox ("Solaris", cbg, false);
mac = new Checkbox ("Mac OS", cbg, false);
add (winXP);
add (winVista);
add (solaris);
add (mac);
winXP.addItemListener (this);
winVista.addItemListener (this);
solaris.addItemListener (this);
mac.addItemListener (this);
}
public void itemStateChanged (ItemEvent ie)
{
repaint ();
}
// Display current state of the check boxes.
public void paint (Graphics g)
{
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox ().getLabel ();
g.drawString (msg, 6, 100);
}
}
Output:
os.add ("Solaris");
os.add ("Mac OS");
// add items to browser list
browser.add ("Internet Explorer");
browser.add ("Firefox");
browser.add ("Opera");
browser.add ("Chrome");
// add choice lists to window
add (os);
add (browser);
// register to receive item events
os.addItemListener (this);
browser.addItemListener (this);
}
public void itemStateChanged (ItemEvent ie)
{
repaint ();
}
// Display current selections.
public void paint (Graphics g)
{
msg = "Current OS: ";
msg += os.getSelectedItem ();
g.drawString (msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem ();
g.drawString (msg, 6, 140);
}
}
Output:
List Constructor
1. List() throws HeadlessException: It creates a list control that allows only one item to
be selected at any one time.
2. List(int numRows) throws HeadlessException: Here, the value of numRows
specifies the number of entries in the list that will always be visible.
3. List(int numRows, boolean multipleSelect) throws HeadlessException: If
multipleSelect is true, then the user may select two or more items at a time. If it’s false,
then just one item could also be selected.
Method of Lists
1. void add(String name): To add a selection to the list, use add(). Here, the name is the
name of the item being added. It adds items to the end of the list.
2. void add(String name, int index): It also adds items to the list but it adds the items at
the index specified by the index.
3. String getSelectedItem(): It determines which item is currently selected. It returns a
string containing the name of the item. If more than one item is selected, or if no
selection has been made yet, null is returned.
4. int getSelectedIndex(): It determines which item is currently selected. It returns the
index of the item. The first item is at index 0. If more than one item is selected, or if no
selection has yet been made, -1 is returned.
5. String[] getSelectedItems(): It allows multiple selections. It returns an array
containing the names of the currently selected items.
6. int[] getSelectedIndexes(): It also allows multiple selections. It returns an array
containing the indexes of the currently selected items.
7. int getItemCount(): It obtains the number of items in the list.
8. void select(int index): It is used to set the currently selected item with a zero-based
integer index.
9. String getItem(int index): It is used to obtain the name associated with the item at the
given index. Here, the index specifies the index of the desired items.
Example
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ListDemo" width=300 height=180> </applet> */
public class ListDemo extends Applet implements ActionListener
{
List os, browser;
String msg = "";
public void init ()
{
os = new List (4, true);
browser = new List (4, false);
// add items to os list
os.add ("Windows XP");
os.add ("Windows Vista");
os.add ("Solaris");
os.add ("Mac OS");
// add items to browser list
browser.add ("Internet Explorer");
browser.add ("Firefox");
browser.add ("Opera");
browser.select (1);
// add lists to window
add (os);
add (browser);
// register to receive action events
os.addActionListener (this);
browser.addActionListener (this);
}
public void actionPerformed (ActionEvent ae)
{
repaint ();
}
// Display current selections.
public void paint (Graphics g)
{
int idx[];
msg = "Current OS: ";
idx = os.getSelectedIndexes ();
for (int i = 0; i < idx.length; i++)
msg += os.getItem (idx[i]) + " ";
g.drawString (msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem ();
g.drawString (msg, 6, 140);
}
}
Output:
Scrollbar Constructor
1. Scrollbar() throws HeadlessException: It creates a vertical scrollbar.
2. Scrollbar(int style) throws HeadlessException: It allows you to specify the
orientation of the scrollbar. If the style isScrollbar.VERTICAL, a vertical scrollbar is
created. If a style is Scrollbar.HORIZONTAL, the scroll bar is horizontal.
3. Scrollbar(int style, int initialValue, int thumbSize, int min, int max) throws
HeadlessException: Here, the initial value of the scroll bar is passed in initialValue.
The number of units represented by the peak of the thumb is passed in thumbSize. The
minimum and maximum values for the scroll bar are specified by min and max.
Scrollbar Methods
1. void setValues(int initialValue, int thumbSize, int min, int max): It is used to set the
parameters of the constructors.
2. int getValue(): It is used to obtain the current value of the scroll bar. It returns the
current setting.
3. void setValue(int newValue): It is used to set the current value. Here, newValue
specifies the new value for the scroll bar. When you set a worth, the slider box inside
the scroll bar is going to be positioned to reflect the new value.
4. int getMaximum(): It is used to retrieve the minimum values. They return the
requested quantity. By default, 1 is the increment added to the scroll bar.
5. int getMaximun(): It is used to retrieve the maximum value. By default, 1 is the
increment subtracted from the scroll bar.
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="SBDemo" width=300 height=200> </applet> */
public class ScrollbarDemo extends Applet implements AdjustmentListener, MouseMotionListener
{
String msg = "";
Scrollbar vertSB, horzSB;
public void init ()
{
int width = Integer.parseInt (getParameter ("width"));
int height = Integer.parseInt (getParameter ("height"));
vertSB = new Scrollbar (Scrollbar.VERTICAL, 0, 1, 0, height);
horzSB = new Scrollbar (Scrollbar.HORIZONTAL, 0, 1, 0, width);
add (vertSB);
add (horzSB);
// register to receive adjustment events vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);
addMouseMotionListener (this);
}
public void adjustmentValueChanged (AdjustmentEvent ae)
{
repaint ();
}
//Update scroll bars to reflect mouse dragging.
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:
➢ After the applet, the type of window we will most often create is derived from Frame. We will
use it to create child windows within applets, and top-level or child windows for applications.
➢ It creates a standard-style window.
➢ Following are two of Frame‘s constructors:
Frame( )
Frame(String title)
➢ The first form creates a standard window that does not contain a title.
➢ The second form creates a window with the title specified by title.
➢ Note that we cannot specify the dimensions of the window. Instead, we must set the size of
the window after it has been created.
➢ Setting the Windows Dimensions the setSize( ) method is used to set the dimensions of the
window.
➢ The first constructor takes three integers that specify the color as a mix of red, green, and blue.
These values must be between 0 and 255, as in this
Example:
new Color(255, 100, 100); // light red
➢ We can obtain the red, green, and blue components of a color independently using getRed( ),
getGreen( ), and getBlue( ), shown below:
int getRed( )
int getGreen( )
int getBlue( )
➢ Each of these methods returns the RGB color component found in the invoking Color object in
the lower 8 bits of an integer.
getRGB( )
➢ To obtain a packed, RGB representation of a color, use getRGB( ), shown here:
int getRGB( )
➢ The return value is organized as described earlier.
Setting the Current Graphics Color
➢ By default, graphics objects are drawn in the current foreground color. We can change this
color by calling the Graphics method setColor( ):
void setColor(Color newColor)
➢ Here, ̳newColor‘ specifies the new drawing color. We can obtain the current color by
calling getColor( ), shown below:
Color getColor( )
Example:
/*
<applet code="ColorDemo" width=300 height=200>
</applet>
*/
public class ColorDemo extends Applet
{
public void paint(Graphics g)
{
Color c1 = new Color(202, 146, 20);
Color c2 = new Color(110, 169, 107);
Color c3 = new Color(160, 100, 200);
g.setColor(c1);
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.setColor(Color.red);
g.drawLine(40, 25, 250, 180);
g.setColor(c3);
g.drawLine(20, 150, 400, 40);
g.setColor(c2);
g.drawOval(10, 10, 50, 50);
g.fillOval(70, 90, 140, 100);
}
}
Output:
LAYOUT MANAGER
➢ A layout manager is a class that is useful to arrange components in a particular
manner in container or a frame.
➢ Java soft people have created a LayoutManager interface in java.awt package which
is implemented in various classes which provide various types of layouts to arrange
the components. The following classes represents the layout managers in Java:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. CardLayout
5. GridBagLayout
6. BoxLayout
➢ To set a particular layout, we should first create an object to the layout class and pass the
object to setLayout() method. For example, to set FlowLayout to the container:
FlowLayout obj=new FlowLayout();
c. setLayout(obj); // assume c is container
FlowLayout:
➢ FlowLayout is useful to arrange the components in a line one after the other. When a
line is filled with components, they are automatically placed in a next line. This is the
default layout in applets.
Constructors:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
➢ The first form creates the default layout, which centres components and leaves five
pixels of space between each component. The second form lets you specify how each
line is aligned. Valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
➢ The third constructor allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="FlowLayoutDemo" width=240 height=200>
</applet>
*/
(or)
/*
<applet code="FlowLayoutDemo" width=240 height=200>
</applet> */
public class FlowLayoutDemo extends Applet
{
Checkbox m,f;
public void
init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT));
m = new Checkbox("Male", true);
f = new Checkbox("Female");
add(m );
add(f);
}
}
BorderLayout:
➢ BorderLayout is useful to arrange the components in the four borders of the frame as
well as in the centre.
➢ The borders are identified with the names of the directions. The top border is
specified as ‘North’, the right side border as ‘East’, the bottom one as ‘South’ and the
left one as ‘West’. The centre is represented as ‘Centre’.
Constructors:
BorderLayout( ) BorderLayout(int horz, int vert)
➢ The first form creates a default border layout. The second allows you to specify the
horizontal and vertical space left between components in horz and vert, respectively.
➢ BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.EAST
BorderLayout.WEST
BorderLayout.NORTH
➢ When adding components, you will use these constants with the following form of add( ),
which is defined by Container:
void add(Component compObj, Object region)
➢ Here, compObj is the component to be added, and region specifies where the
componentwill be added.
Example:
import java.applet.*;
import java.util.*;
/*
<applet code="BorderLayoutDemo" width=400 height=200>
</applet>
*/
public class BorderLayoutDemo extends Applet
{
public void init()
{
setLayout(new BorderLayout());
add(new Button("Top"),BorderLayout.NORTH);
add(new Button("Bottom"),BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "PVPSIT started by SAGTE in
1998.\n";add(new TextArea(msg),
BorderLayout.CENTER);
}
}
GridLayout:
➢ GridLayout is useful to divide the container into a 2D grid form that contains several rows
and columns. The container is divided into equal-sized rectangle; and one component is
placed in each rectangle.
Constructors:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
➢ The first form creates a single-column grid layout. The second form creates a grid
layout with the specified number of rows and columns. The third form allows you to specify
the horizontal and vertical space left between components in horz and vert, respectively.
Either numRows or numColumns can be zero. Specifying numRows as zero allows for
unlimitedlength columns. Specifying numColumns as zero allows for unlimited-length rows.
Example:
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo2" width=150 height=150>
</applet>
*/
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CardLayoutDemo" width=300 height=100>
</applet>
*/
public class CardLayoutDemo extends Applet implements ActionListener
{
Button b1,b2,b3,b4;
Panel p;
CardLayout card;
public void init()
{
b1 = new Button("Button 1");
b2 = new Button("Button 2");
b3 = new Button("Button 3");
b4 = new Button("Button 4");
p=new Panel();
card=new
CardLayout(20,20);
p.setLayout(card);
p.add("First",b1);
p.add("Second",b2);
p.add("Third",b3);
p.add("Fourth",b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
add(p);
}
public void actionPerformed(ActionEvent ae)
{
card.next(p);
}
}
GridBagLayout:
➢ A GridBagLayout class represents grid bag layout manager where the components are
arranged in rows and columns. In this layout the component can span more than one row or
column and the size of the component can be adjusted to fit the display area.
➢ When positioning the components by using grid bag layout, it is necessary to apply some
constraints or conditions on the components regarding their position, size and place in or
around the components etc. Such constraints are specified using GridBagConstrinats class.
➢ In order to create GridBagLayout, we first instantiate the GridBagLayout class by using its
only no-argument constructor and defining it as the current layout manager.
GridBagLayout layout=new GridBagLayout();
setLayout(layout);
➢ To apply constraints on the components, we should first create an object to
GridBagConstrinats class, as
GridBagConstrinats gbc =new GridBagConstrinats();
➢ This will create constraints for the components with default value. The other way to
specify the constraints is by directly passing their values while creating the
GridBagConstrinats as
GridBagConstrinats gbc= new GridBagConstrinats( int gridx, int gridy, int gridwidth,
int gridheight, double weightx, doubleweighty, int anchor, int fill, Insets insets, int
ipadx, int ipady );
➢ To set the constraints use setConstraints() method in GridBagConstrinats class
and itsprototype
void setConstraints(Component comp, GridBagConstraints cons);
➢ Constraint fields Defined by GridBagConstraints:
Field Purpose
Specifies the location of a component within a cell. The
default is GridBagConstraints.CENTER. Others are
GridBagConstraints.EAST
GridBagConstraints.WEST
int anchor GridBagConstraints.SOUTH
GridBagConstraints.NORTH
GridBagConstraints.NORTHEAST
GridBagConstraints.NORTHWEST
GridBagConstraints.SOUTHEAST
GridBagConstraints.SOUTHWEST
Specifies the X coordinate of the cell to which the
int gridx component will be added.
Specifies the Y coordinate of the cell to which the
int gridy component will be added.
Specifies the height of component in terms of cells. The
int gridheight
default is 1.
Specifies the width of component in terms of cells. The
int gridwidth
default is 1.
double weightx Specifies a weight value that determines the horizontal
spacing between cells and the edges of the container that
holds them. The default value is 0.0. The greater the weight,
the more space that is allocated.
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="GridBagDemo" width=200 height=100>
</applet>
*/
}
}
EVENT HANDLING
Events:
➢ An event is an object that describes a state change in a source. It can be generated as a
consequence of a person interacting with the elements in a GUI. Some of the activities that
cause events to be generated are pressing a button, entering a character via the keyboard,
selecting an item in a list, and clicking the mouse.
Event Sources:
➢ A source is an object that generates an event. Generally sources are components. Sources
may generate more than one type of event.
➢ A source must register listeners in order for the listeners to receive notifications about a
specific type of event. Each type of event has its own registration method. Here is the general
form:
public void addTypeListener (TypeListener el )
➢ Here, Type is the name of the event, and el is a reference to the event listener. For example,
the method that registers a keyboard event listener is called addKeyListener( ).
➢ A source must also provide a method that allows a listener to unregister aninterest in a
specific type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el )
Event Listeners:
➢ A listener is an object that is notified when an event occurs. It hastwo major requirements.
1. It must have been registered with one or more sources to receivenotifications
about specific types of events.
2. It must implement methods to receive and process these notifications.
➢ The methods that receive and process events are defined in a set of interfaces found in
java.awt.event package
➢ In this scheme, the listener simply waits until it receives an event. Once an event is received,
the listener processes the event and then returns. The advantage of this design is that the
application logic that processes events is cleanly separated from the user interface logic that
generates those events.
➢ A user interface element is able to “delegate” the processing of an event to a separate piece
of code. In the delegation event model, listeners must register with a source in order to
receive an event notification. This provides an important benefit: notifications are sent only
tolisteners that want to receive them.
Sources of Events:
➢ The java.awt.event package provides many event classes and Listener interfaces for event
handling. At the root of the Java event class hierarchy is EventObject, which is in java.util.
It is the super class for all events. Its one constructor is shown here:
EventObject(Object src) - Here, src is the object that generates this event. EventObject
contains two methods:
getSource( ) - returns the source of the event.
toString( ) - toString( ) returns the string equivalent of the event.
➢ The class AWTEvent, defined within the java.awt package, is a subclass of EventObject.
It is the superclass (either directly or indirectly) of all AWT-based events used by the
delegation event model. Its getID( ) method can be used to determine the type of the event.
The signature of this method is shown here:
int getID( )
➢ The package java.awt.event defines many types of events that are generated by various
userinterface elements
Event Class Description Listener Interface
Generated when a button is pressed, a list
ActionEvent item is double-clicked, or a menu item is ActionListener
selected.
AdjustmentEvent Generated when a scroll bar is manipulated. AdjustmentListener
Generated when a component is hidden,
ComponentEvent moved, resized, or becomes visible. ComponentListener
Generated when a component is added to or
ContainerEvent ContainerListener
removed from a container.
Generated when a component gains or
FocusEvent FocusListener
losses keyboard focus.
Abstract super class for all component input
InputEvent event classes.
Generated when a check box or list item is
ItemEvent clicked ItemListener
Generated when input is received from the
KeyEvent keyboard. KeyListener
Generated when the mouse is dragged,
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 139
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Method Description
public void add(Component c) inserts a component on this component.
sets the size (width and height) of the
public void setSize(int width,int height) component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
changes the visibility of the component, by
public void setVisible(boolean status) default false.
➢ However, because of possible conflicts between the modifiers used by keyboard events and
mouse events, and other issues, the following extended modifier values were added:
META_DOWN_MASK SHIFT_DOWN_MASK
➢ The first two events are generated when any key is pressed or released. The last event
occurs only when a character is generated. Remember, not all keypresses result in
characters. For example, pressing shift does not generate a character.
➢ There are many other integer constants that are defined by KeyEvent. For example, VK_0
through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbersand
letters.
EventListener Interfaces:
➢ An event listener registers with an event source to receive notifications about the
events of a particular type. Various event listener interfaces defined in the
java.awt.event package are given below:
Interface Description
Defines the actionPerformed() method to receive and process
ActionListener action events.
void actionPerformed(ActionEvent ae)
Defines five methods to receive mouse events, such as when a
mouse is clicked, pressed, released, enters, or exits a component
void mouseClicked(MouseEvent me)
MouseListener void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
Defines two methods to receive events, such as when a mouse is
MouseMotionListener dragged or moved.
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
Defines the adjustmentValueChanged() method to receive and
AdjustmentListner process the adjustment events.
void adjustmentValueChanged(AdjustmentEvent ae)
Defines the textValueChanged() method to receive and process an
TextListener event when the text value changes.
void textValueChanged(TextEvent te)
Defines seven window methods to receive events.
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
WindowListener void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
Defines the itemStateChanged() method when an item has been
ItemListener
void itemStateChanged(ItemEvent ie)
This interface defines two methods: windowGainedFocus( ) and
windowLostFocus( ). These are called when a window gains or
WindowFocusListener loses input focus. Their general forms are shown here:
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
This interface defines four methods that are invoked when a
component is resized, moved, shown, or hidden. Their general
forms are shown here:
ComponentListener void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
This interface contains two methods. When a component is added
to a container, componentAdded( ) is invoked. When a
component is removed from a container, componentRemoved( )
ContainerListener is invoked.
Their general forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
// save coordinates
mouseX = me.getX( );
mouseY = me.getY( );
msg ="Up";
repaint( );
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
// save coordinates
mouseX = me.getX( );
mouseY = me.getY( );
msg = "*";
showStatus("Dragging mouse at " + mouseX + ", " +mouseY); repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me)
{
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current
X,Ylocation. public void paint(Graphics g)
{
g.drawString(msg, mouseX, mouseY);
}
}
Output:
Adapter Classes:
➢ Java provides a special feature, called an adapter class, that can simplify the creation of
event handlers in certain situations. An adapter class provides an empty implementation of
all methods in an event listener interface. Adapter classes are useful when you want to
receive and process only some of the events that are handled by a particular event listener
interface.
For example,
MouseListener MouseAdapter
void mouseClicked(MouseEvent me) void mouseClicked(MouseEvent me){ }
void mouseEntered(MouseEvent me) void mouseEntered(MouseEvent me) { }
void mouseExited(MouseEvent me) void mouseExited(MouseEvent me) { }
void mousePressed(MouseEvent me) void mousePressed(MouseEvent me) { }
void mouseReleased(MouseEvent me) void mouseReleased(MouseEvent me) { }
INNER CLASSES:
➢ Inner class is a class defined within another class, or even within an expression.
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="InnerClassDemo" width=300 height=100>
</applet>
*/
UNIT – V
Swing : Introduction to Swing – Hierarchy of swing components. Containers -Top level
containers -JFrame - JWindow - JDialog - JPanel - JButton - JToggleButton - JCheckBox -
JRadioButton - JLabel, JTextField – JtextArea – Jlist – JcomboBox - JScrollPane.
public void setLayout(LayoutManager m) sets the layout manager for the component.
Swing Containers
Swing containers can be classified into three main categories:
➢ Top-level containers:
JFrame, JWindow, and JDialog
➢ General-purpose containers:
JPanel, JScrollPane,JToolBar,JSplitPane, and JTabbedPane
➢ Special-purpose containers:
JInternalFrame and JLayeredPane
myapplet.html
<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body> </html>
JFrame :
➢ The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI.
➢ Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
Nested Class
Modifier and Type Class Description
Fields
Modifier and Type Field Description
Constructors
Constructor Description
Useful Methods
Modifier and Type Method Description
Called by the
constructor methods to
protected JRootPane createRootPane()
create the default
rootPane.
Called by the
protected void frameInit() constructors to init the
JFrame properly.
Provides a hint as to
whether or not newly
created JFrames should
have their Window
setDefaultLookAndFeelDecorated(boolean
static void decorations (such as
defaultLookAndFeelDecorated)
borders, widgets to
close the window,
title...) provided by the
current look and feel.
It gets the
TransferHandler getTransferHandler() transferHandler
property.
Example
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JFrameExample {
public static void main(String s[]) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Example");
JButton button = new JButton();
button.setText("Button");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(200, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output
JPanel
➢ The JPanel is the simplest container class. It inherits the JComponents class and provides a
space for an application to attach other components. It does not have a title bar.
➢ JPanel is a lightweight Java container that offers a place to organize and arrange other GUI
(graphical user interface) components. It is used as a building element in Swing apps to create
intricate layouts. JPanel is easily attached to other containers, such as JFrame or another
JPanel, because it inherits from the JComponent class.
➢ JPanel is suited for embedding into other containers or as a component of a larger GUI because
it lacks a title bar and other decorations, in contrast to top-level containers like JFrame. JPanel
is frequently used by developers to handle events related to its enclosed components, manage
layout with layout managers like FlowLayout, GridLayout, or BorderLayout, and group
relevant components together.
JPanel(LayoutManager layout, boolean Creates a new JPanel with the specified layout
isDoubleBuffered) manager and buffering strategy.
Example:
PanelExample.java
import java.awt.*;
import javax.swing.*;
public class PanelExample {
PanelExample()
{
JFrame f= new JFrame("Panel Example");
JPanel panel=new JPanel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
JButton b1=new JButton("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
JButton b2=new JButton("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:
Explanation
➢ The use of JPanel in a Swing application is demonstrated by the following Java code. It
specifies a class called PanelExample, whose constructor, PanelExample(), is in charge of
setting up and arranging the GUI elements.
➢ A JFrame object with the name f and the label "Panel Example" is instantiated within the
constructor. In order to instantiate two JButton objects, b1 and b2, their corresponding
boundaries and background colors are set when a JPanel object called panel is formed.
➢ The panel is added to the frame, and the buttons are added to the panel. The frame is made
visible after its size and layout are both set to null. In summary, this code generates a JFrame
with a JPanel that has two buttons, each with a different background colour and uses a null
layout to position them.
JDialog :
➢ The JDialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Dialog class.
➢ Unlike JFrame, it doesn't have maximize and minimize buttons.
JDialog(Frame owner, String title, boolean It is used to create a dialog with the specified
modal) title, owner Frame and modality.
Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output:
JButton :
➢ The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
Output:
b.setBounds(100,100,100, 40);
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ButtonExample();
} }
Output:
JToggleButton
➢ JToggleButton is used to create toggle button, it is two-states button to switch on or off.
Nested Classes
Modifier and Type Class Description
JToggleButton(String text, Icon icon, boolean It creates a toggle button with the specified
selected) text, image, and selection state.
Methods
Modifier and Type Method Description
It returns a string
protected String paramString() representation of this
JToggleButton.
Example
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class JToggleButtonExample extends JFrame implements ItemListener {
public static void main(String[] args) {
new JToggleButtonExample();
}
private JToggleButton button;
JToggleButtonExample() {
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
JCheckBox:
➢ The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
JCheckBox class declaration
Let's see the declaration for javax.swing.JCheckBox class.
public class JCheckBox extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description
Example
import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:
cb1.setBounds(100,100,150,20);
cb2=new JCheckBox("Burger @ 30");
cb2.setBounds(100,150,150,20);
cb3=new JCheckBox("Tea @ 10");
cb3.setBounds(100,200,150,20);
b=new JButton("Order");
b.setBounds(100,250,80,30);
b.addActionListener(this);
add(l);add(cb1);add(cb2);add(cb3);add(b);
setSize(400,400);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
float amount=0;
String msg="";
if(cb1.isSelected()){
amount+=100;
msg="Pizza: 100\n";
}
if(cb2.isSelected()){
amount+=30;
msg+="Burger: 30\n";
}
if(cb3.isSelected()){
amount+=10;
msg+="Tea: 10\n";
}
msg+="-----------------\n";
JOptionPane.showMessageDialog(this,msg+"Total: "+amount);
}
public static void main(String[] args) {
new CheckBoxExample();
}
}
Output:
JRadioButton :
➢ The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.
➢ It should be added in ButtonGroup to select one radio button only.
Example :
import javax.swing.*;
public class RadioButtonExample {
JFrame f;
RadioButtonExample(){
f=new JFrame();
JRadioButton r1=new JRadioButton("A) Male");
JRadioButton r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);
Output:
JLabel :
➢ The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.
Example
import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
}}
Output:
JTextField :
➢ The object of a JTextField class is a text component that allows the editing of a single line text.
It inherits JTextComponent class.
Example
import javax.swing.*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
JTextArea :
➢ The object of a JTextArea class is a multi-line region that displays text. It allows the editing of
multiple-line text. It inherits the JTextComponent class. An editable and showing multi-line
text component in Java is represented by the JTextArea class, which is a component of the
javax.swing package.
➢ It is a flexible instrument for managing text in graphical user interfaces (GUIs). It provides
extra features designed for multi-line text display and input while inheriting fundamental text
editing and manipulation functionality from the JTextComponent class, from which it extends.
➢ This class is frequently used in graphical user interface (GUI) applications where users must
enter or view text that crosses numerous lines, like in text editors, chat programmes, or form
fields. Developers may design dynamic, interactive interfaces for effective text input and
manipulation with JTextArea.
JTextArea Class Declaration
Let's see the declaration for javax.swing.JTextArea class.
public class JTextArea extends JTextComponent
➢ JTextArea is a subclass of JTextComponent that offers additional features specifically designed
for handling multi-line text material in addition to text editing and rendering functionality.
➢ JTextArea is a tool that developers can use to build interactive graphical user interface (GUI)
applications. These apps can be used to show enormous amounts of text, allow user input in
text areas, or construct text editors that support multiple lines of text.
Constructor Description
Example
import javax.swing.*;
public class TextAreaExample
{
TextAreaExample(){
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 178
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Explanation
➢ A JTextArea called area and a JFrame named f are initialized by the code. The text "Welcome
to javatpoint" is initialized in the JTextArea.
➢ The position and size of the JTextArea are set to (10,30) with a wide of 200 pixels and a height
of 200 pixels using the setBounds() method.
➢ The JFrame is then updated with the JTextArea. The layout manager is specifically set to null,
and the JFrame is configured with a size of 300x300 pixels. When the JFrame's visibility is set
to true, it is finally visible on the screen.
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}
Output:
Explanation
➢ The above Java program generates a Swing GUI application with a JTextArea for text input, a
JButton to count the characters and words in the text input, and a JLabels display for the
results.The constructor of the TextAreaExample class initialises the JFrame and the GUI
elements. The word count and character count are displayed by two JLabels (l1 and l2),
respectively.
➢ To begin the counting process, a JButton (b) with the label "Count Words" is created and a
JTextArea (area) is configured for text input. The TextAreaExample class itself is selected as
the button's ActionListener. Every element is included in the JFrame (f).
➢ To handle button clicks, the ActionListener interface requires the implementation of the
actionPerformed function. getText() is used to retrieve the text entered into the JTextArea upon
clicking of the button. The split() method is then used to divide the text into words based on
whitespace, utilising the regular expression "\s" to do so.
➢ The setText() function on the JLabels is used to count and show the number of words and
characters.The Main method creates the TextAreaExample object and initialises and displays
the GUI for the user.
JList:
➢ The object of JList class represents a list of text items. The list of text items can be set up so
that the user can choose either one item or multiple items. It inherits JComponent class.
Example
import javax.swing.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4");
JList<String> list = new JList<>(l1);
list.setBounds(100,100, 75,75);
f.add(list);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample(); }}
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 181
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
Output:
}
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample();
}}
Output:
JComboBox :
➢ The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
void removeAllItems() It is used to remove all the items from the list.
Example
import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20);
f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Output:
Output:
JScrollPane :
➢ A JscrollPane is used to make scrollable view of a component. When screen size is limited, we
use a scroll pane to display a large component or a component whose size can change
dynamically.
Constructors
Constructor Purpose
Useful Methods
Modifier Method Description
Example
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
public class JScrollPaneExample {
private static final long serialVersionUID = 1L;
private static void createAndShowGUI() {
// Create and set up the window.
final JFrame frame = new JFrame("Scroll Pane Example");
// Display the window.
frame.setSize(500, 500);
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 186
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set flow layout for the frame
frame.getContentPane().setLayout(new FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCR
OLLBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy
(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Output:
JWindow :
➢ JWindow is a part of Java Swing and it can appear on any part of the users desktop. It is
different from JFrame in the respect that JWindow does not have a title bar or window
management buttons like minimize, maximize, and close, which JFrame has. JWindow can
contain several components such as buttons and labels.
Constructor of the class are:
1. JWindow() : creates an empty Window without any specified owner
2. JWindow(Frame o) :creates an empty Window with a specified frame as its owner
3. JWindow(Frame o) : creates an empty Window with a specified frame as its owner
4. JWindow(Window o) : creates an empty Window with a specified window as its owner
5. JWindow(Window o, GraphicsConfiguration g) : creates an empty window with a
specified window as its owner and specified graphics Configuration.
6. JWindow(GraphicsConfiguration g) :creates an empty window with a specified
Graphics Configuration g.
Commonly used methods
1. setLayout(LayoutManager m) : sets the layout of the Window to specified layout
manager
2. setContentPane(Container c) : sets the ContentPane property of the window
3. getContentPane() : get the container which is the ContentPane for this Window
4. add(Component c): adds component to the Window
5. isVisible(boolean b): sets the visibility of the Window, if value of the boolean is true
then visible else invisible
6. update(Graphics g) : calls the paint(g) function
7. remove(Component c) : removes the component c
8. getGraphics() : returns the graphics context of the component.
9. getLayeredPane() : returns the layered pane for the window
10. setContentPane(Container c) :sets the content pane for the window
11. setLayeredPane(JLayeredPane l) : set the layered pane for the window
12. setRootPane(JRootPane r) : sets the rootPane for the window
13. setTransferHandler(TransferHandler n) : Sets the transferHandler property, which is a
mechanism to support transfer of data into this component.
14. setRootPaneCheckingEnabled(boolean enabled) : Sets whether calls to add and
setLayout are forwarded to the contentPane.
15. setRootPane(JRootPane root) :Sets the rootPane property of the window.
16. setGlassPane(Component glass) : Sets the glassPane property of the window.
17. repaint(long time, int x, int y, int width, int height): Repaints the specified rectangle of
this component within time milliseconds.
18. remove(Component c): Removes the specified component from the window.
19. isRootPaneCheckingEnabled() : Returns whether calls to add and setLayout are
forwarded to the contentPane or not .
20. getTransferHandler() : returns the transferHandler property.
21. getRootPane() : Returns the rootPane object for this window.
22. getGlassPane() : Returns the glassPane object for this window.
program to create a simple JWindow
// if button is pressed
public void actionPerformed(ActionEvent e)
{ String s = e.getActionCommand();
if (s.equals("click")) {
// create a window
JWindow w = new JWindow(f);
// set panel
JPanel p = new JPanel();
// create a label
JLabel l = new JLabel("this is a window");
// set border
p.setBorder(BorderFactory.createLineBorder(Color.black));
p.add(l);
w.add(p);
// set background
p.setBackground(Color.red);
// setsize of window
w.setSize(200, 100);
// set visibility of window
w.setVisible(true);
// set location of window
w.setLocation(100, 100);
}
}
}
Output :
program to create a multiple JWindow .( where one window is the owner of the other )
// java program to create a multiple JWindow .( where one window is the owner of the other )
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solveit extends JFrame implements ActionListener {
// frame
static JFrame f;
// windows
JWindow w, w1;
// object of class
static solveit s;
// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");
// create a object
s = new solveit();
// create a panel
JPanel p = new JPanel();
JButton b = new JButton("click");
// add actionlistener to button
b.addActionListener(s);
// add button to panel
p.add(b);
f.add(p);
// set the size of frame
f.setSize(400, 400);
f.show();
}
// if button is pressed
public void actionPerformed(ActionEvent e)
{
String s1 = e.getActionCommand();
if (s1.equals("click")) {
// create a window
w = new JWindow(f);
// set panel
JPanel p = new JPanel();
// create a label
JLabel l = new JLabel("this is first window");
// create a button
JButton b = new JButton("Click me");
// add Action listener
b.addActionListener(s);
// set border
p.setBorder(BorderFactory.createLineBorder(Color.black));
p.add(l);
p.add(b);
w.add(p);
// set background
p.setBackground(Color.red);
// setsize of window
w.setSize(200, 100);
// set visibility of window
w.setVisible(true);
// set location of window
w.setLocation(100, 100); }
else {
// create a window
w1 = new JWindow(w);
// set panel
JPanel p = new JPanel();
// create a label
JLabel l = new JLabel("this is the second window");
// set border
p.setBorder(BorderFactory.createLineBorder(Color.black));
p.add(l);
w1.add(p);
// set background
p.setBackground(Color.blue);
// setsize of window
w1.setSize(200, 100);
// set visibility of window
w1.setVisible(true);
// set location of window
w1.setLocation(210, 210);
}
}
}
Output :
AIM:
To write a Java program that prompts the user for an integer and then prints out all the prime
numbers up to that Integer.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To prompt the user to enter an integer using a Scanner object.
Step 3 : To use a for loop to iterate from 2 to the user-input integer.
Step 4 : For each number in the range, we call the isPrime method to check if it's a prime number.
Step 5 : If the number is prime, we print it out.
Step 6 : The isPrime method checks if a number is prime by iterating from 2 to the square root of the
number and checking if it has any divisors. If it does, it returns false. Otherwise, it returns true.
Step 7 : Stop the program.
PROGRAM:
import java.io.*;
import java.util.Scanner;
OUTPUT:
D:\Naresh>set path=C:\jdk1.5.0\bin
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
2.Matrix Multiplication.
AIM :
To write a Java program to multiply two given matrices.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To read the dimensions of the two matrices from the user.
Step 3 : To check if the matrices can be multiplied by checking if the number of columns in the first
matrix is equal to the number of rows in the second matrix.
Step 4 : To get the elements of the matrices from the user.
Step 5 : To multiply the matrices using the for loops.
Step 6 : To print the result of the matrix multiplication using the for loops.
Step 7 : Stop the program.
PROGRAM:
import java.io.*;
import java.util.Scanner;
OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin
D:\Naresh >javac MatrixMultiplication.java
D:\Naresh >java MatrixMultiplication
Enter the number of rows and columns in the first matrix:
2
2
Enter the number of rows and columns in the second matrix:
2
2
Enter the elements of the first matrix:
1
3
5
7
Enter the elements of the second matrix:
2
4
6
8
Result of matrix multiplication:
20 28
52 76
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
AIM:
To write a Java program that displays the number of characters, lines and words in a text.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To use a Scanner object to read input from the user.
Step 3 : To prompt the user to enter a text and store it in the text variable.
Step 4 : To calculate the number of characters in the text using the length() method.
Step 5 : To calculate the number of lines in the text using the countLines method, which splits the text
into an array of lines using the split method with a regular expression that matches line breaks
(\\r?\\n).
Step 6 : To calculate the number of words in the text using the countWords method, which splits the
text into an array of words using the split method with a regular expression that matches one
or more whitespace characters (\\s+).
Step 7 : To print out the text statistics, including the number of characters, lines, and words.
Step 8 : Stop the program.
PROGRAM:
import java.io.*;
import java.util.Scanner;
public class TextStat
{
public static void main(String[ ] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a text: ");
String text = scanner.useDelimiter("ctrl+Z").next();
int cCount = text.length( );
int lCount = countLines(text);
int wCount = countWords(text);
System.out.println("Text statistics:");
System.out.println("Characters: " + cCount);
System.out.println("Lines: " + lCount);
System.out.println("Words: " + wCount);
}
public static int countLines(String text)
{
String[ ] lines = text.split("\\r?\\n");
return lines.length;
}
OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin
Text statistics:
Characters: 37
Lines: 2
Words: 8
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
AIM :
To Generate random numbers between two given limits using Random class and print
messages according to the range of the value generated.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To prompt the user to enter the lower and upper limits of the range.
Step 3 : To create a Random object to generate random numbers.
Step 4 : To use the nextInt method to generate a random number between the lower and upper limits.
Step 5 : To add 1 to the difference between the upper and lower limits to include the upper limit in
the range.
Step 6 : To print out the generated random number.
Step 7 : To use if-else statements to determine which third of the range the random number falls into
and print out a corresponding message.
Step 8 : Stop the program.
PROGRAM:
import java.io.*;
import java.util.Random;
import java.util.Scanner;
else
{
System.out.println("Random number is in the upper third of the range.");
}
}
}
OUTPUT:
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
5. String Manipulation
AIM:
To write a program to do String Manipulation using CharacterArray and perform to find the
String length , Finding a character at a particular position and Concatenating two strings.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To prompt the user to enter two strings using a Scanner object.
Step 3 : To convert the strings to character arrays using the toCharArray() method.
Step 4 : We calculate the length of each string by accessing the length property of the character array.
Step 5 : To prompt the user to enter a position to find the character in the first string.
Step 6 : To check if the entered position is valid (i.e., between 0 and the length of the string minus 1).
If it is, we print the character at that position. Otherwise, we print an error message.
Step 7 : To concatenate the two strings by creating a new character array that is large enough to hold
both strings, and then using the System.arraycopy() method to copy the characters from each
string into the new array.
Step 8 : Stop the program.
PROGRAM:
import java.io.*;
import java.util.Scanner;
else
{
System.out.println("Invalid position. Please enter a position between 0 and " +
(charArray1.length - 1));
}
char[ ] concatenatedArray = concatenate(charArray1, charArray2);
System.out.println("Concatenated string: " + new String(concatenatedArray));
}
public static char[ ] concatenate(char[ ] charArray1, char[ ] charArray2)
{
char[ ] result = new char[charArray1.length + charArray2.length];
System.arraycopy(charArray1, 0, result, 0, charArray1.length);
System.arraycopy(charArray2, 0, result, charArray1.length, charArray2.length);
return result;
}
}
OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
AIM :
To Write a program to perform the string operations as like String Concatenation , Search a
substring and to extract substring from given string using String class.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To prompt the user to enter two strings using a Scanner object.
Step 3 : To concatenate the two strings using the + operator.
Step 4 : To prompt the user to enter a substring to search in the first string.
Step 5 : To use the contains( ) method to check if the substring is present in the first string.
Step 6 : To prompt the user to enter the starting and ending indices of the substring to extract from the
first string.
Step 7 : To check if the entered indices are valid (i.e., between 0 and the length of the string minus 1,
and the starting index is less than or equal to the ending index). If they are, we use the
Substring( ) method to extract the substring. Otherwise, we print an
error message.
Step 8 : Stop the program.
PROGRAM:
import java.io.*;
import java.util.Scanner;
else
{
System.out.println("Substring not found in string 1");
}
System.out.print("Enter the starting index of the substring to extract from string 1: ");
int sIndex = scanner.nextInt( );
scanner.nextLine();
System.out.print("Enter the ending index of the substring to extract from string 1: ");
int eIndex = scanner.nextInt( );
scanner.nextLine();
if (sIndex >= 0 && eIndex >= 0 && sIndex < str1.length() && eIndex < str1.length() &&
sIndex <= eIndex)
{
String exSubstring = str1.substring(sIndex, eIndex);
System.out.println("Extracted substring: " + exSubstring);
}
else
{
System.out.println("Invalid indices. Please enter valid indices between 0 and " +
(str1.length() - 1));
}
}
}
OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
AIM :
To write a program to perform string operations as like Length of a string , Reverse a string
and Delete a substring from the given string using String Buffer class.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To prompt the user to enter a string using a Scanner object.
Step 3 : To convert the string to a StringBuffer object.
Step 4 : To calculate the length of the string using the length( ) method.
Step 5 : To reverse the string using the reverse( ) method.
Step 6 : To prompt the user to enter a substring to delete from the string.
Step 7 : To use the indexOf( ) method to find the index of the substring in the string.
If the substring is found, we use the delete( ) method to delete the substring from the string.
Otherwise, we print an error message.
Step 8 : Stop the program.
PROGRAM:
import java.io.*;
import java.util.Scanner;
public class StringBufferOperations
{
public static void main(String[ ] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine( );
StringBuffer stringBuffer = new StringBuffer(str);
System.out.println("Length of the string: " + stringBuffer.length());
stringBuffer.reverse( );
System.out.println("Reversed string: " + stringBuffer);
System.out.print("Enter a substring to delete from the string: ");
String substring = scanner.nextLine();
int index = stringBuffer.indexOf(substring);
if (index != -1)
{
stringBuffer.delete(index, index + substring.length());
System.out.println("String after deleting the substring: " + stringBuffer);
}
else
{
System.out.println("Substring not found in the string");
} }
}
OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
8. Multithread Application
AIM :
To write a java program that implements a multi-thread application that has three threads. First
thread generates random integer every 1 second and if the value is even, second thread computes the
square of the number and prints. If the value is odd, the third thread will print the value of cube of the
number.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To define a Shared class to hold the generated number, a flag to indicate whether the number
is even or odd, and a flag to indicate whether to stop the execution.
Step 3 : To define three threads: GeneratorThread, SquareThread, and CubeThread.
Step 4 : The GeneratorThread generates random numbers every 1 second and sets the number in
the Shared object. It stops generating numbers after 5 iterations.
Step 5 : The SquareThread and CubeThread wait for a number to be generated and then check
whether the number is even or odd. If the number is even, the SquareThread computes the
square of the number and prints it. If the number is odd, the CubeThread computes the cube
of the number and prints it.
Step 6 : To start all three threads in the main method.
Step 7 : Once the GeneratorThread finishes generating 5 numbers, it sets the stop flag to true, which
causes the SquareThread and CubeThread to exit their loops and terminate.
Step 8 : Stop the program.
PROGRAM:
import java.io.*;
import java.util.Random;
class Shared
{
private int number;
private boolean isEven;
private boolean stop;
public synchronized void setNumber(int number)
{
this.number = number;
this.isEven = (number % 2 == 0);
notifyAll( );
}
public synchronized int getNumber( )
{
while (number == 0 && !stop)
{
try
{
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 207
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
wait();
}
catch (InterruptedException e)
{
Thread.currentThread( ).interrupt( );
}
}
if (stop)
{
return 0;
}
int temp = number;
number = 0;
return temp;
}
public synchronized boolean isEven( )
{
return isEven;
}
public synchronized void setStop(boolean stop)
{
this.stop = stop;
notifyAll( );
}
public synchronized boolean isStop( )
{
return stop;
}
}
OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
AIM :
To write a threading program which uses the same method asynchronously to print the
numbers 1to10 using Thread1 and to print 90 to100 using Thread2.
ALGORITHM:
Start 1 : Start the program.
Start 2 : To define two threads: Thread1 and Thread2.
Start 3 : Thread1 prints numbers 1 to 10 with a delay of 100 milliseconds between each print.
Start 4 : Thread2 prints numbers 90 to 100 with a delay of 100 milliseconds between each print.
Start 5 : To start both threads in the main method using the start( ) method.
Start 6 : Since both threads are running concurrently, the output will be interleaved, with Thread1
and Thread2 printing numbers asynchronously.
Start 7 : Stop the program.
PROGRAM:
import java.io.*;
OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin
Thread2: 97
Thread1: 8
Thread1: 9
Thread2: 98
Thread1: 10
Thread2: 99
Thread2: 100
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
AIM:
To write a program to demonstrate the Arithmetic Exception , Number Format Exception ,
ArrayIndexOutofBoundException and NegativeArraySizeException.
ALGORITHM:
Start 1 : Start the program.
Start 2 : To define a main method that demonstrates the use of four different exceptions.
Start 3 : For each exception, we use a try block to attempt to execute code that will throw the
exception.
Start 4 : To use a catch block to catch the exception and print a message indicating that the exception
was caught.
Start 5 : For the ArithmeticException, we attempt to divide by zero, which is undefined in
mathematics.
Start 6 : For the NumberFormatException, we attempt to parse a string that is not a valid integer.
Step 7 : For the ArrayIndexOutOfBoundsException, we attempt to access an index of an array that
is out of bounds.
Step 8 : For the NegativeArraySizeException, we attempt to create an array with a negative size.
Step 9 : Stop the program.
PROGRAM:
import java.io.*;
public class ExceptionDemo
{
public static void main(String[ ] args)
{
// a. Arithmetic Exception
try
{
int a = 10;
int b = 0;
int result = a / b;
System.out.println("Result: " + result);
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException caught: " + e.getMessage( ));
}
// b. Number Format Exception
try
{
String str = "bca";
int num = Integer.parseInt(str);
System.out.println("Number: " + num);
}
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 215
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,
catch (NumberFormatException e)
{
System.out.println("NumberFormatException caught: " + e.getMessage( ));
}
// c. ArrayIndexOutOfBoundsException
try
{
int[ ] arr = new int[5];
System.out.println(arr[10]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException caught: " + e.getMessage( ));
}
// d. NegativeArraySizeException
try
{
int[ ] arr = new int[-5];
}
catch (NegativeArraySizeException e)
{
System.out.println("NegativeArraySizeException caught: " + e.getMessage( ));
}
}
}
OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
AIM :
To write a Java program that reads on file name from the user, then displays information about
whether the file exists, whether the file is readable, whether the file is writable, the type of file and the
length of the file in bytes
ALGORITHM:
Step 1 : Start the program.
Step 2 : To use a Scanner object to read input from the user.
Step 3 : To prompt the user to enter a file name, and store the input in String variable fileName.
Step 4 : To create a File object using the fileName.
Step 5 : To use various methods of the File class to retrieve information about the file, such as:
• exists( ): whether the file exists
• canRead( ): whether the file is readable
• canWrite( ): whether the file is writable
• isFile( ): whether the file is a regular file (not a directory)
• isDirectory( ): whether the file is a directory
• length( ): the length of the file in bytes
Step 6 : To print out the information about the file to the console.
Step 7 : Stop the program.
PROGRAM:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
else if (file.isDirectory( ))
{
System.out.println("File Type: Directory");
}
else
{
System.out.println("File Type: Unknown");
}
System.out.println("File Length: " + file.length( ) + " bytes");
}
}
OUTPUT:
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
AIM :
To write a program to accept a text and change its size and font. Include bold italic options.
Use frames and controls.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To create a JTextArea to display the text.
Step 3 : To create a JSpinner to select the font size.
Step 4 : To create a JComboBox to select the font.
Step 5 : To create two JCheckBoxes to select bold and italic styles.
Step 6 : To add action listeners to the controls to update the font of the text area when the user makes a
selection.
Step 7 : To create a panel to hold the controls and add it to the frame.
Step 8 : To add the text area to the frame and set the default close operation to exit the application
when the frame is closed.
Step 9 : Stop the program.
PROGRAM:
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
fontSizeSpinner.addChangeListener(new ChangeListener( )
{
public void stateChanged(ChangeEvent e)
{
int fontSize = (int) ((Integer) fontSizeSpinner.getValue( ));
textArea.setFont(new Font(textArea.getFont( ).getName( ), textArea.getFont( ).getStyle( ),
fontSize));
}
});
// Create font combo box
fontComboBox = new JComboBox(new String[ ] {"Arial", "Times New Roman", "Courier
New"});
fontComboBox.addActionListener(new ActionListener( )
{
public void actionPerformed(ActionEvent e)
{
String fontName = (String) fontComboBox.getSelectedItem( );
textArea.setFont(new Font(fontName, textArea.getFont( ).getStyle( ),
textArea.getFont().getSize( )));
}
});
// Create bold and italic check boxes
boldCheckBox = new JCheckBox("Bold");
boldCheckBox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int style = textArea.getFont( ).getStyle( );
if (boldCheckBox.isSelected( ))
{
style |= Font.BOLD;
}
else
{
style &= ~Font.BOLD;
}
textArea.setFont(new Font(textArea.getFont( ).getName( ), style,
textArea.getFont( ).getSize( )));
}
});
italicCheckBox = new JCheckBox("Italic");
italicCheckBox.addActionListener(new ActionListener( )
{
public void actionPerformed(ActionEvent e)
{
OUTPUT:
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
13 .Event Handling
AIM:
To write a Java program that handles all mouse events and shows the event name at the center
of the window when a mouse event is fired. (Use adapter classes).
ALGORITHM:
Step 1 : Start the program.
Step 2 : To create a JPanel subclass called MouseEventHandler that handles all mouse events.
Step 3 : To add a JLabe1 to the panel to display the event name.
Step 3 : To use adapter classes MouseAdapter and MouseMotionAdapter to handle mouseevents.
Step 4 : The MouseAdapter class provides empty implementations for all mouse events, and override
the methods we're interested in.
Step 4 : To use the MouseMotionAdapter class provides empty implementations for mouse motion
events.
Step 5 : When a mouse event is fired, we call the showEvent method to update the label text and
repaint the label.
Step 6 : In the main method, to create a JFrame and add an instance of MouseEventHandler to it.
Step 7 : To set the frame's default close operation to exit on close and make the frame visible.
Step 8 : Run the program, and to see the event name displayed at the center of the window when you
perform mouse events such as clicking, moving, dragging, entering, and exiting the window.
Step 9 : Stop the program.
PROGRAM:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public MouseEventHandler()
{
label = new JLabel("", JLabel.CENTER);
add(label);
addMouseListener(new MouseAdapter( )
{
public void mousePressed(MouseEvent e)
{
showEvent("Mouse Pressed");
}
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
showEvent("Mouse Dragged");
}
public void mouseMoved(MouseEvent e)
{
showEvent("Mouse Moved");
}
});
}
OUTPUT:
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
AIM :
To write a Java program that works as a simple calculator. Use a grid layout to arrange buttons
for the digits and for the +, -,*, % operations. Add a text field to display the result. Handle any
possible exceptions like divide by zero.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To create a JFrame with a JTextField at the top to display the result and a JPanel with a
grid layout to arrange the buttons for the digits and operations.
Step 3 : To use an ActionListener to handle button clicks. When a digit button is clicked, we append
the digit to the text field. When an operation button is clicked, to store the current number and
operation, and clear the text field. When the "=" button is clicked, we perform the operation
and display the result.
Step 4 : To handle exceptions like divide by zero and invalid input by displaying an error message in
the text field.
Step 5 : Stop the program.
PROGRAM:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
setSize(200, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand( );
if (command.equals("="))
{
try
{
number2 = Double.parseDouble(resultField.getText( ));
switch (operation)
{
case '+' :
result = number1 + number2;
break;
case '-' :
result = number1 - number2;
break;
case '*' :
result = number1 * number2;
break;
case '/' :
if (number2 != 0)
{
result = number1 / number2;
}
else
{
resultField.setText("Error: Division by zero");
return;
}
break;
}
resultField.setText(String.valueOf(result));
}
catch (NumberFormatException ex)
{
resultField.setText("Error: Invalid input");
}
}
RESULT :
Thus, the above program has been created successfully and the outputs are verified.
AIM:
To write a Java program that simulates a traffic light. The program lets the user select one of
three lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message
with ―stop‖ or ―ready‖ or ―go‖ should appear above the buttons in a selected color. Initially there is
no message shown.
ALGORITHM:
Step 1 : Start the program.
Step 2 : To create a JFrame with two panels: one for the message label and one for the radio buttons.
Step 3 : To use a ButtonGroup to ensure that only one radio button can be selected at a time.
Step 4 : To add an ActionListener to each radio button to update the message label
when a button is selected. The message label's text and color are changed based on the selected
button.
Step 5 : Run the program, and you'll have a simple traffic light simulator that displays a message based
on the selected light color!.
Step 6 : Stop the program.
PROGRAM:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public TrafficLight()
{
// Create a panel for the message label
JPanel messagePanel = new JPanel();
messagePanel.setLayout(new FlowLayout());
messageLabel = new JLabel("", SwingConstants.CENTER);
messageLabel.setPreferredSize(new Dimension(200, 30));
messagePanel.add(messageLabel);
// Create a panel for the radio buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(yellowButton);
group.add(greenButton);
buttonPanel.add(redButton);
buttonPanel.add(yellowButton);
buttonPanel.add(greenButton);
// Add action listeners to the radio buttons
redButton.addActionListener(new RadioButtonListener());
yellowButton.addActionListener(new RadioButtonListener());
greenButton.addActionListener(new RadioButtonListener());
// Add the panels to the frame
add(messagePanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
setSize(250, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private class RadioButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (redButton.isSelected())
{
messageLabel.setText("STOP");
messageLabel.setForeground(Color.RED);
}
else if (yellowButton.isSelected())
{
messageLabel.setText("READY");
messageLabel.setForeground(Color.YELLOW);
}
else if (greenButton.isSelected())
{
messageLabel.setText("GO");
messageLabel.setForeground(Color.GREEN);
}
}
}
public static void main(String[ ] args)
{
new TrafficLight();
}
}
OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin
RESULT :
Thus, the above program has been created successfully and the outputs are verified.