0% found this document useful (0 votes)
60 views232 pages

23uca04 - Java Class Notes

The document outlines the syllabus for a Bachelor of Computer Applications course on Programming in Java at Arignar Anna College, covering key topics such as object-oriented concepts, inheritance, multithreading, AWT and Swing components, and Java development environment. It provides a detailed introduction to Java, its history, features, and the architecture of the Java Virtual Machine (JVM). The document serves as a comprehensive guide for students to understand the foundational elements and practical aspects of Java programming.

Uploaded by

mindcreativity6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views232 pages

23uca04 - Java Class Notes

The document outlines the syllabus for a Bachelor of Computer Applications course on Programming in Java at Arignar Anna College, covering key topics such as object-oriented concepts, inheritance, multithreading, AWT and Swing components, and Java development environment. It provides a detailed introduction to Java, its history, features, and the architecture of the Java Virtual Machine (JVM). The document serves as a comprehensive guide for students to understand the foundational elements and practical aspects of Java programming.

Uploaded by

mindcreativity6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 232

ARIGNAR ANNA COLLEGE

(ARTS & SCIENCE)


KRISHNAGIRI

BACHELOR OF COMPUTER APPLICATIONS


23UCA04 - PROGRAMMING IN JAVA

Submitted
By
M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

ASST.PROFESSOR

DEPARTMENT OF COMPUTer APPLICATIONS


ARIGNAR ANNA COLLEGE ( ARTS & SCIENCE )

KRISHNAGIRI
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

23UCA04 – PROGRAMMING IN JAVA


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.

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 1


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 2


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ 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

Flying bird Non flying bird

Robin Swallow Penguin kiwi


Polymorphism:
➢ Polymorphism is another important OOP concept. Polymorphism means the ability to take
more than one form .An operation may exhibit different behaviour in different instances .The
behaviour depends upon the types of data used in the operation .For example consider the
operation of addition .For two numbers ,The operation will generate a sum .
➢ If the operands are strings ,then the operation would produce a third string by concatenation
.The process of making an operator to exhibit different behaviours in different instances is
known as operator overloading.
Dynamic binding:
➢ Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding means that the code associated with a given procedure call is not known
until the time of call at runtime .
➢ It is associated with polymorphism and inheritance. It is otherwise known as late binding.
Message Passing:
➢ An Object-oriented program consists of a set of objects that communicate with each other. The
process of programming in an object –oriented language, therefore, involves the following
basic steps:
1. Creating classes that define objects and their behaviour
2. Creating objects from class definitions, and
3. Establishing communication among objects.
➢ Objects communicate with one another by sending and receiving information much the way
people pass messages to one another. Message Passing involves specifying the name of the
object, the name of the function (message) and information to be sent. Example:
Employee. Salary(name)

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 3


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Introduction to JAVA[Just Another Virtual Architecture]:


 Java is a true object oriented language.
 Java is similar to c++.
 Java features can be modified from c++.
 There are no header files in JAVA.
 Java doesn’t support multiple inheritance, operator overloading, global variable, pointers.

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.

JAVA DEVELOPMENT ENVIRONMENT


➢ Java environment includes a large number of development tools, and hundreds of classes and
methods.
➢ The development tolls are part of the system known as Java Development Kit (JDK) and the
classes and methods are part of the Java Standard Library (JSL) also known as API
(Application Programming Interface).
E.g.
✓ AppletViewer (for viewing java applets).
✓ javac (java compiler)
✓ java (java Interpreter, which runs applets and application by reading and
✓ interpreting byte code files)
✓ javah (produces header files for use with native methods)

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 4


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

✓ 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

Java Source HTML Files


Code javadoc

javac

Header Files
javah
Java Class File

java jdb

Java Program
Output

JAVA BUZZWORDS (OR) FEATURES OF JAVA:

 Compiled & Interpreted


 Platform Independent & Portable.
 Object –Oriented.
 Robust & Secure.
 Distributed
 Familiar ,Simple & Small
 Multithreaded & Interactive.
 High Performance.
 Dynamics and Extensible.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 5


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

1. Compiled & Interpreted:


• Java combines both approaches.
• So java is a two-stage system.
• Java compiler translates source code into byte code.
• Byte codes are not machine instructions
• Java interpreter can generates machine code can be directly executed by machine that is
running java program.
• So java is compiled & an interpreted language.
2. Platform Independent & Portable
• It is portable.
• Java programs can be easily moved from one system to another anywhere and anytime.
• Changes in os, processors & system resources will not force any in java programs.
• So java has become a popular language for programming on internet.
3. Portable:
• 2 ways:
• Java compiler-→ byte code instruction can be implemented on any machine.
• Size of primitive data types is machine independent.
4. Object Oriented:
• It is true object oriented language.
• Java is an object.
• All codes & data are placed inside of objects& classes.
• It is an extensible set of classes arranged in packages use by inheritance.
• So java is simple & easy to extend.
5. Robust:
• Java is a robust language.
• It Provides Safeguards to ensure reliable code.
• It has strict compile time & run time checking for data type.
• It has concept of execution handling captures series errors & eliminates risk.
6. Secured:
• Java is a secure language.
• Java is used on Internet.
• Thread of viruses & abuse of resources.
7. Distributed:
• It is a distributed language for creating applications on Internet or network.
• Ability to share both data & programs.
• It can open, access remote objects on Internet as easily.
8. Simple, Small, Familiar:
• Java is simple & small language.
• It also eliminates operator overloading & multiple Inheritance, goto statement& preprocessor
header & pointers.
• It is a familiar to existing programmers.
9. Multithreaded and Interactive
• Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded
programs.
• This features improves interactive performance of graphical application.
10. Dynamic and Extensible
• Java is a Dynamic language. Java is capable of dynamically linking in new class libraries,
methods and objects.
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 6
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

• Java support functions in other language c& c++.


• These functions are Native Functions.
• Native Functions are linked dynamically at runtime.
What is JVM (Java Virtual Machine)?
➢ The JVM (Java Virtual Machine) is a virtual machine, an abstract computer that has its own
ISA, memory, stack, heap, etc.
➢ It runs on the host OS and places its demands for resources on it.
➢ The JVM (Java Virtual Machine) is a specification and can have different implementations,
as long as they adhere to the specs.
JVM (Java Virtual Machine) Architecture

➢ 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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 7


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ 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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 8


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ Run-Time Constant Pool


✓ The JVM maintains a per-class/per-type data structure that acts as the symbol table (one of its
many roles) while linking the loaded classes.
➢ Native Method Stacks
✓ When a thread invokes a native method, it enters a new world in which the structures and
security restrictions of the Java virtual machine no longer hamper its freedom.
✓ A native method can likely access the runtime data areas of the virtual machine (it depends
upon the native method interface), but can also do anything else it wants.
4. Execution Engine
The execution engine is responsible for executing the bytecode, it has three different components:
➢ Garbage Collection
✓ The JVM manages the entire lifecycle of objects in Java. Once an object is created, the
developer need not worry about it anymore.
✓ In case the object becomes dead (that is, there is no reference to it anymore), it is ejected from
the heap by the GC using one of the many algorithms – serial GC, CMS, G1, etc.
✓ During the GC process, objects are moved in memory. Hence, those objects are not usable
while the process is going on.
✓ The entire application has to be stopped for the duration of the process. Such pauses are called
'stop-the-world' pauses and are a huge overhead. GC algorithms aim primarily to reduce this
time.
➢ Interpreter
✓ The interpreter Interprets the bytecode. It interprets the code fast but it's slow in execution.
➢ JIT Complier
✓ The JIT stands for Just-In-Time. The JIT compiler is a main part of the Java runtime
environment and it compiles bytecodes to machine code at runtime.
5. Java Native Interface (JNI)
✓ Java Native Interface (JNI) interacts with the native method libraries which are essential for the
execution.
6. Native Method Libraries
✓ Native method libraries are the collection of C and C++ libraries (native libraries) which are
essential for the execution.

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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 9


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

✓ float data type


✓ double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte


➢ Boolean Data Type
✓ The Boolean data type is used to store only two possible values: true and false. This data type
is used for simple flags that track true/false conditions.
✓ The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
1. Boolean one = false
➢ Byte Data Type
✓ The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
✓ The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Example:
1. byte a = 10, byte b = -20

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 10


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ Short Data Type


✓ The short data type is a 16-bit signed two's complement integer. Its value-range lies between -
32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
✓ The short data type can also be used to save memory just like byte data type. A short data type
is 2 times smaller than an integer.
Example:
1. short s = 10000, short r = -5000
➢ Int Data Type
✓ The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
✓ The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
1. int a = 100000, int b = -200000
➢ Long Data Type
✓ The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0.
✓ The long data type is used when you need a range of values more than those provided by int.
Example:
1. long a = 100000L, long b = -200000L
➢ Float Data Type
✓ The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers.
✓ The float data type should never be used for precise values, such as currency. Its default value
is 0.0F.
Example:
1. float f1 = 234.5f
➢ Double Data Type
✓ The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float.
✓ The double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.
Example:
1. double d1 = 12.3
➢ Char Data Type
✓ The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).
✓ The char data type is used to store characters.
Example:
1. char letterA = 'A'

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 11


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ 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.

1. int data=50;//Here data is variable


TYPES OF VARIABLES (OR) SCOPE AND LIFE TIME OF VARIABLES:
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) Local Variable
✓ A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
✓ A local variable cannot be defined with "static" keyword.
2) Instance Variable
✓ A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
✓ It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
✓ A variable that is declared as static is called a static variable. It cannot be local. You can create
a single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
✓ Advertisement
Example to understand the types of variables in java
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 12


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example: Add Two Numbers


public class Simple{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Output:
20
Example: Widening
public class Simple{
public static void main(String[] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}}
Output:
10
10.0
Example: Narrowing (Typecasting)
public class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}}
Output:
10.5
10
Example: Overflow
class Simple{
public static void main(String[] args){
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}}
Output:
130
-126

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 13


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example: Adding Lower Type


class Simple{
public static void main(String[] args){
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
System.out.println(c);
}}
Output:
20

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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 14


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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:

Operand1 relational operator operand2


Program
class large
{
public static void main(String args[])
{
int a=9,b=8;
if(a>b)
System.out.println(“ the largest value is ”+a);
else
System.out.println(“ the largest value is”+b);
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 15


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

3.LOGICAL OPERATOR:
✓ The logical operator is used to test more than one condition.
Logical Operator Meaning
&& logical AND
|| logical OR
! logical NOT

Working of AND,OR: Working of NOT:


Op1 op2 op&&op2 op1||op2 Op1 !op1

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 16


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

 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:

Exp1? Exp2 : Exp3

Exp -> expressions.


• Exp1 is evaluated and if it is true,exp2 is evaluated and the value is assign to variable.
• Exp1 is false exp3 is evaluated and the value is assign to variable.

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->).

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 17


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 18


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

The general form is


if(condition)
{
True block statement;
}
else
{
False block statement;
}
Statement-n;

• If the condition is true, the true block statements will be executed.


• if the condition is false, the false block statements will be executed.
• In either care either the true block or the false block will be executed.
/*largest of two numbers*/
class large
{
public static void main(String args[])
{
int a=9,b=6;
if(a>b)
System.out.println(“a is large“);
else
System.out.println(“b is large”);
}
Nested if-else statement or dangling else:
➢ If an if-else statement is placed with in another if-else statement, it is a nested if-else statement.
The general for is,
if(condition-1)
{
if(condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
Statement-n;

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 19


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

• If condition -1 is true and condition-2 is false,statement-2 will be executed.


• If condition-1 is false, statement-3 will be executed.
Eg:
1)/*Largest of three numbers*/
class largest
{
public static void main(String args[])
{
int a=9,b=6,c=5;
if(a>b)
{
if(a>c)
{
System.out.println( a);
}
else
{
System.out.println( c);

}
}
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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 20


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

The general format:

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”);
}

Conditional Operator Statement:


➢ It is a operator and is used to make two way decision
General Format:
exp1?:exp2:exp3

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 21


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);
}

ITERATION STATEMENTS / LOOPING STATEMENTS:


1. WHILE LOOP
➢ It is an entry control loop.The genaral form is
Syntax:
while(condition)
{
Body of the loop;
}
Execution:
• If the condition is true the body of the loop will be executed.
• If the condition is false the control is terminate at the loop.
/*sum of digits*/
class sum
{
public static void main(String args[])
{
int num=123,r,q=0;
while(num>0)
{
r=num%10;
q=q+r;
num=num/10;
}
System.out.println (num); }

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 23


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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:

for(initialiazation ; condition ; increment and decrement)


{
body of loop;
}

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*/

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 24


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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;
}

Nested For Loop:


➢ It is entry control loop.
General Form:

for(initialization; condition; increment and decrement)


{
for(initialization; condition; increment and decrement)
{
body of loop;
}
}

/*to find the addition of 2 matrix*/


class matrix
{
public static void main(String args[])
{
int matrix1[ ][ ]=new int[3][3],matrix2[ ][ ]=new int[3][3], ans[ ][ ]=new int[3][3],i,j;
matrix1[0][0]=3;
matrix1[0][1]=23;
matrix1[0][2]=23;
matrix1[1][0]=31;
matrix1[1][1]=32;
matrix1[1][2]=13;
matrix2[0][0]=4;
matrix2[0][1]=5;
matrix2[0][2]=6;
matrix2[1][0]=31;
matrix2[1][1]=2;
matrix2[1][2]=1;

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 25


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

label name-> variable name.


Types:
1) forward jump/goto
2) backward jump/goto.

Forward Jump
➢ If the label statement is placed after the goto statement.
General format

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 26


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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;
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 27


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Statement Label Vs Case Label


Statement label Case label
1) The label must be variable names 1) The case labels may be integer constant or
single character constants
2)The labeled statement can be placed anywhere 2) The case labeled should be placed after the
in the program case keyword

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.

Flow chart for Type Conversion


➢ This type of type conversion is also called Widening Type Conversion/ Implicit Conversion/
Casting Down.
➢ In this case, as the lower data types with smaller sizes are converted into higher ones with a
larger size, there is no chance of data loss. This makes it safe for usage.

➢ 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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 28


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ Example for Type Conversion in Java:


public class Main {
public static void main(String[] args) {
int intType = 20;
// Float is of higher data type than int
float floatType = intType;

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.

Flow chart for Type Casting


➢ Type casting is also called Narrowing Type Casting/ Explicit Conversion/ Casting Up. In
this case, as the higher data types with a larger size are converted into lower ones with a
smaller size, there is a chance of data loss.
➢ This is the reason that this type of conversion does not happen automatically.

➢ 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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 29


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Difference Between Type Casting and Type Conversion


Parameter Type Casting Type Conversion

Type casting is a process in


Type conversion is a process in which
which the programmer manually
Definition the data type is automatically converted
converts one data type into
into another data type
another data type.

Explicitly done by the


Can be implicit or explicit, depending on
Method programmer using casting
the language and context.
operators.

Function calls, constructors, or other


Syntax (newType) variable
conversion methods.

Can involve conversions between


Compatibility Must be compatible data types.
incompatible data types.

The result may involve data loss or


Immediate change in the data
Change rounding errors, depending on the
type of the variable.
conversion m

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.

1. ONE DIMENSIONAL ARRAY:


Declaration Of One Dimensional Array:
➢ A list of items can be given one variable name using only one subscript. The subscript must be
integer constant.
general format:
data type arrayname[size];

eg.
int number[15];
char name[10];
storage process:
number[0]=23;
number[1]=33;
number[2]=53;
number[3]=63;
number[4]=73;

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 30


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.,

Initialization Of One-Dimentional Array:


➢ After an array is declared its elements must be initialized. otherwise they will contain
“garbage”.
general format:
type array_name[size]={list of values}

➢ The values in the list are separated by commas.


for eg.
int number[3]={1,5,7}
the value stored as,
number[0]=1;
number[1]=5;
number[2]=7;
program:
/*initialiazing and printing the value*/
class array
{
public static void main(String args[])
{
int i,a[4]={4,6,7,8};
for(i=0;i<4;i++)
{
System.out.println(a[i]);
}
}
Array Length:
• All arrays store the allocated size in variable named length.
• To obtain length of the array a using a.length.
• Int asize = a.length;
• This information will be useful in manipulation of arrays when their sizes are not
known.

2. TWO DIMENSIONAL ARRAY:


 Array variables can store a list of values.
 2DArrays are stored in memory.
 Each dimension of the array is indexed from zero to its maximum size minus one.
 1st index selects row & second index selects column within that row.
general format:
type array_name[size][size];

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 32


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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];

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 33


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

SIMPLE JAVA PROGRAM


class sample
{
public static void main(String args[])
{
System.out.println(“Welcome to java”);
}
}

THE FIRST LINE:


❖ Class one declares a class, which is an object oriented construct. Class is a keyword and
declares that a new class definition follows.
THE THIRD LINE
❖ Public static void main(String a[]) defines a method named main.
❖ Every java application program must include the main() method.
❖ This is the starting point for the interpreter to begin the execution of the program.
❖ A java application can have any number of classes but only one of them must include a main
method to initiate the execution.
❖ Public the keyword Public is an access specifier that declares the main method as unprotected
and therefore making it accessible to all other classes. This is similar to the C++ public
modifier.
Static:
❖ Neat appears the keyword static, which declares this method as one that belongs to the entire
class and not part of any objects of the class.
❖ It (main) must always be declared as static since the interpreter uses this method before any
objects are created.
Void:
❖ The type modifier void states that the main method does not return any value.

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.,

Application Programming Interface:


 Java standard library (JSL) or APL includes hundreds of classes & methods are grouped into
several functional Packages.
/*factorial*/
class factorial
{
public static void main(String args)
{
long int i,n=5,fact=1;
clrscr();
for(i=1;i<n;i++)
{
fact=fact*i;
System.out.println(“factorial”+fact);
}
}
CLASSES , OBJECTS AND METHODS :
What is class?
➔ A class is a user defined data type.
➔ A class is essentially a description of how to make an objet that contain fields and methods.
Define a class:
➔ Class type has been defined, can create variable of that type using declaration.
➔ Variable is called as instance of class.
Syntax:
class classname [extend super class name]
{
[Fields declaration;]
[Methods declaration;]
}
inside square bracket is optional.
e.g:
class empty
{
}
➔ Classname & superclassname are java identifiers.
➔ Extends->properties of superclass extended to classname class this is called inheritance.
Field declaration:
➔ Data is grouped in a class by placing data fields inside body of the class definition.
➔ These variables are created instance variable because they are created whenever an object of
the class is instantiated.
Eg:
class rectangle
{
int length;
int width;
}
➔ Rectangle -2 integer type instance variable. Instance variable are known as member variable.
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 35
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();

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 36


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

i) Declares variable to hold object reference.


ii)Assigns object reference to variable.
rectangle rect1;
rect1=new Rectangle();
rect1 is a reference to rectangle object both statement are combined.
rectangle recr1=new rectangle();
Create any number of object.
rectangle rect1=new rectangle();
rectangle rect2=new rectangle();
Assigning 1 object reference variable to another.
rectangle r1=new rectangle ();
rectangle r2=r1;
Accessing class members:
 can’t access instance variable and method directly.
 use object& dot operator
 object name.variable name=value;
 object name.method name(parameter-list);
 object name is name of the object.
 variable name is name of the in instance variable inside the object.
 method name is method.
 parameter-list is a comma separated list of actual values.
1) Instance variables of rectangle class may be accessed and assigned values.
rect1.length=15;
rect2.width=10;
2) Method getdata can be used to assign values to the instance variable
rect1.getdata(15,10);
Passes 15,10 values to x & y.
Compute area of the rectangle using 2 ways.
1) To access instance variables using dot operator and compute the area.
int area1=rect1.length* rect1.width;
2 ) To call rectarea inside the class .
int area1=rect1.rectarea();
Program:
class rectangle
{
int length , width ;
void getdata(int x,int y)
{
length=x;
width=y;
}
int rectarea()
{
int area=length*width;
{
int area=length*width;
return(area);}}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 37


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);
}}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 38


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

STATIC MEMBERS and METHODS:


Class contain 2 sections
1. Declares variable instance variable .
2. Declares method instance method.
Access using dot operator:
➔ To define a member is common to all object & accessed without using a particular object.
➔ Member belongs to the class rather than the object.
Eg:
static int count;
static int max(int x,int y);
• There are static members.
• Static member are associated with the class.
• Static variable & method are called as class variable & method.
• It can be called without using objects.
Program:
class mathoperation
{
static float mul(float x,float y)
{
return x/y;
}
class mathapplication
{
public static void main(String args[])
float a=mathoperation.mul(4.0,5.0);
float b=mathoperation.divide(a,2.0);
System.out.println(“b=’’+b);
}
}
RULES:
• Can only call other static methods.
• Can only access static data.
• Can’t refer to this or super.
NESTING OF METHOD:
➔ A method can be called by using only its name by another method of the same
class.This is known as nesting of methods.
Eg program:
class nesting
{
int m,n;
nesting(int x,int y)
{
m=x;
n=y;
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 39


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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));
}}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 40


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 41


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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));
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 42


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

String ss = new String(str.toString());


int pos = ss.indexOf(“languages”);
str.insert(process,”oriented”);
System.out.println(“Modified String:”+str);
str.setcharAt(6,’_’);
System.out.println(“String now:”+str);
str.append(“improves security”);
System.out.println(“Appended String:”+str);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 43


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.

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.

1. SINGLE LEVEL INHERITANCE:


A one class features are derived from another class is called single level inheritance.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 44


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 45


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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
{
……………….
……………..
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 46


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 47


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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)

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 48


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

{
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;

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 49


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 50


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 51


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 52


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 53


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Difference Between this and super keyword


The following table describes the key difference between this and super:
this super

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.

Difference Between this() and super() Constructor


this() super()

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.

ABSTRACT METHOD AND CLASSES


➢ A method final we ensure that the method is not redefined in a subclass.
➢ The method can never be subclassesd.
➢ We can indicate that a method must always be aedefined in a subclasses, thus making
overriding compulsory.
➢ This is done using the modifier keyword abstract in the method definition.
abstract class Shape
{
abstract void draw();
}
➢ When a class contains one or more abstract methods.
➢ It should be declared abstract
While using abstract classes, we must satisfy the following conditions:
➢ We cannot use abstract classes to instantiate objects directly.
Eg:
Shape s = new shape()
➢ Is illegal because shape is an abstract class.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 54


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ The abstract methods of an abstract class must be defined in its class.


➢ We cannot declare abstract constructors or abstract static methods.

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( );
}}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 55


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

→ Declaring Abstract Methods:


 Any class that contains one or more abstract methods must also be declared abstract and
cannot declare abstract constructor or abstract static method.
 To declare an abstract method the general format is
Syntax:
Abstract type method_name(parameterlist);
Ex:
Abstract class test
{
Abstract void shap( );
}
DYNAMIC METHOD DISPATCH IN JAVA
➢ Dynamic method dispatch is also known as run time polymorphism.
➢ It is the process through which a call to an overridden method is resolved at runtime.
➢ This technique is used to resolve a call to an overridden method at runtime rather than compile
time.
➢ To properly understand Dynamic method dispatch in Java, it is important to understand the
concept of upcasting because dynamic method dispatch is based on upcasting.

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");
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 56


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public void on(){


System.out.println("Turning on Phone...");
}
}
class SmartPhone extends Phone{
public void music(){
System.out.println("Playing music...");
}
public void on(){
System.out.println("Turning on SmartPhone...");
}
}
public class CWH {
public static void main(String[] args) {
Phone obj = new SmartPhone(); // Yes it is allowed
// SmartPhone obj2 = new Phone(); // Not allowed
obj.showTime();
obj.on();
// obj.music(); Not Allowed
}
}
OUTPUT
Time is 8 am
Turning on SmartPhone...
Note: The data members can not achieve the run time polymorphism.
package com.company;
class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
public void on(){
System.out.println("Turning on Phone...");
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 57


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

class SmartPhone extends Phone{


public void music(){
System.out.println("Playing music...");
}
public void on(){
System.out.println("Turning on SmartPhone...");
}
}
public class cwh_49_dynamic_method_dispatch {
public static void main(String[] args) {
// Phone obj = new Phone(); // Allowed
// SmartPhone smobj = new SmartPhone(); // Allowed
// obj.name();
Phone obj = new SmartPhone(); // Yes it is allowed
// SmartPhone obj2 = new Phone(); // Not allowed
obj.showTime();
obj.on();
// obj.music(); Not Allowed
}}
PACKAGES:
Define:
 It is similar to class library.
 Package are way of grouping a variety of class and /or interfaces together.
 Grouping is usually done according to functionality.
 Package act as ’’containers’’ for classes.
Benefits:
1) Classes contained in packages of other program can be easily reused.
2) Classes can be compared with classes in other packages.
3) Packages provide a way to hide classes.
4) Package provide a way for separating “design” from “coding”.

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 58


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

Using system packages:


Java.awt contains various classes for implementing graphical user interface.
Two way of accessing classes
1) Use fully qualified classes name of the classes done by using package name containing classes &
then adding class name to using dot operator.
Java.awt.color
2) To use a class in a number of places in program or to use many of classes contained in a package
import packagename.classname;
Or
import packagename.;
Ex:
import java.awt.*;
Naming convention:
 Packages can be named using standard java naming rules.
 Packages begin with lowercase letters.
 It is used to differentiate package names from class names
 All class names begin with an uppercase letter.
double y=java.lang.math.sqrt(x);
 Method begin with lowercase letters
java.awt.point pts[];
 An array of point type objects using fully qualified class name.
Creating package:
• Declare name of the package using package keyword followed by a package name.
• This must be first statement in a java source file.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 59


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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()
{

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 60


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 61


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

o/p:
class A
class B
m=10

Import multiple package:


package pack1;
public class teacher
{---------}
public class student
{---------}
package pack2;
public class courses
{--------}
public class student
{---------}
import pack1.*;
import pack2.*;
student student1;

Adding a class to a package:


package p1;
public classA
{
body of A;
}
• P1-> one public classA

To add another class B to this package.


Steps:
1. Define class & make it public.
2. Place package statement
Package p1;
Eg:
package p1;
public class B
{
pody of B
}
3. Save B.java in p1.
4. Compile B.java create B.class file & place in p1.
• package p1 contain both classes A &B.
Statement:
Import p1.*;
• It will import both of then.
Ex : Program for factorial calculation using package
package fact;
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 62
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public class factorial


{
public void fact(int n)
{
int i,fact=1;
for (i=1;i<=n;i++)
{
fact=fact*i;
}System.out.println("The factorial of" + n + "is:" +fact);
}
}
import fact.*;
import java.io.*;
import java.io.DataInputStream;
class fcal
{
public static void main(String args[])throws IOException
{
int n;
DataInputStream in = new DataInputStream(System.in);
System.out.println("Enter the N value:");
n = Integer.parseInt(in.readLine( ));
factorial f = new factorial( );
f.fact(n);
}
}

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 63


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 64


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public static void main(String args[])


{
mathop obj=new mathop();
obj.circle(2.3);
}
}

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

➢ The public members can be accessed everywhere.


➢ The private members can be accessed only inside the same class.
➢ The protected members are accessible to every child class (same package or other packages).
➢ The default members are accessible within the same package but not outside the package.

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 65


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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();
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 66


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

interface item extends item contants,item methods


{
--------------
}
Implementing interface:
 Interface are used as ‘’superclasses’’.
 Whose properties are inherited by classes..

class classname implements interfacename


{
Body of classname
}
class classname ‘’implements’’ interface interfacename.
Ex:
class classname extends superclass implements interface1,interface2,….
{
Body of classname
}
interface area
{
final static float pi=3.14;
float compute(float x,float y);
}
class rectangle implement area
{
public float compute(float x,float y)
{
return(x*y)
}
}
class circle implements area
{
public float compute area
{
public float compute (float x,float y)
{
return(pi*x*x);
}
}
}
class interface test
{
public static void main(String args[])
{
rectangle rect=new rectangle();
circle cir=new circle();
area area;

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 67


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 68


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 69


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ That is known as exception handling.


➢ Error handling code that performs the following tasks:

1. Find the problem(HIT the exception)


2. Inform that an error has occurred(THROW the exception)
3. Receive the error information(CATCH the exception)
4. Take corrective actions(HANDLE the exceptions)

➢ 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.

ArrayIndexOutOfBoundsException. Caused by bad array indexes.

FileNotFoundException. Caused by an attempt to access a nonexistent


file.
OutOMemoryException. Caused when there’s not enough memory to
allocate a new object.
SecurityException. Caused when an applet tries to perform an
action not allowed by the browser’s security
setting.
StackOverFlowException. Caused when the system runs out of stack
space.
StringIndexOutOfBoundsException. Caused when a program attempts to access a
nonexistent character position in a string.

Syntax of Exception Handling Code:


The basic concept of exception handling are throwing an exception and catching it.
➢ Java uses a keyword try to preface a block of code that is likely to cause an error condition and
“throw” an exception.
➢ A catch block defined by the keyword catch “catches” the exception “thrown” by thee try block and
handle it appropriately.
➢ The catch block is added immediately after the try block.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 70


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Fig)Exception handling mechanism


➢ The catch block too can have one or more statements that are necessary to process the exception.
➢ Catch statement worked like a method definition.
➢ The catch statement is passed a single parameter, which is reference to the exception object thrown
(by the try block).
➢ If the catch parameter matches with yhe type of exception object, then the exception is caught and
statement in the catch block will be execution to terminate.
Program: Using try & catch for exception handling
class Error3
{
public static void main (String args[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c); //EXCEPTION HERE
}
catch (ArithmeticicException e)
{
System.out.println(“Division by zero”);
}
y=a/(b+c);
System.out.println(“y=”+y);
}
}
Output:
Division by zero
Y=1

MULTIPLE CATCH STATEMENTS


• More than one catch statement in catch block
• Java treats the multiple catch statements like cases in a switch statement.
• The first statement whose parameter matches with the exception object will be executed.
• And the remaining statements will skipped.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 71


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 72


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

USING FINALLY STATEMENT


➢ Java supports statement known as finally statement can be used to handle an exception.
➢ Finally block can be used to handle any exception generated within a try block.
➢ It may be added immediately after try block or after last catch block.
SYNTAX:
FIRST METHOD
try
{
…………………………
……………………….}
finally
{
…………………………
………………………..}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 73


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);
}
}}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 74


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

o/p:
E:\java>javac finaldemo.java
E:\java>java finaldemo
y=5

THROWING OUR OWN EXCEPTIONS(PROGRAMMER DEFINED EXCEPTIONS)


➢ Although Java’s built-in exceptions handle most common errors, you will probably want to
create your own exception types to handle situations specific to your applications. This is quite
easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable).
Your subclasses don’t need to actually implement anything—it is their existence in the type
system that allows you to use them as exceptions.
➢ The Exception class does not define any methods of its own. It does, of course, inherit those
methods provided by Throwable. Thus, all exceptions, including those that you create, have
the methods defined by Throwable available to them.
➢ You may also wish to override one or more of these methods in exception classes that you
create.

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);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 75


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 76


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

 java is a multithreaded programming language which means we can develop multithreaded


program using Java. A multithreaded program contains two or more parts that can run
concurrently and each part can handle different task at the same time making optimal use of the
available resources specially when your computer has multiple CPUs.
 By definition multitasking is when multiple processes share common processing resources
such as a CPU. Multithreading extends the idea of multitasking into applications where you
can subdivide specific operations within a single application into individual threads. Each of
the threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
 Multithreading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and
then dies. Following diagram shows complete life cycle of a thread.

Above-mentioned stages are explained here:


• New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
• Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
• Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task.A thread transitions back to the runnable state only when another
thread signals the waiting thread to continue executing.
• Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval expires
or when the event it is waiting for occurs.
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 77
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

• 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:

1. public void run(): is used to perform action for a thread.


2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 78


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

CREATE THREAD BY IMPLEMENTING RUNABLE INTERFACE:


If your class is intended to be executed as a thread then you can achieve this by implementing
Runnable interface. You will need to follow three basic steps:
Step 1:
➢ As a first step you need to implement a run() method provided by Runnable interface. This
method provides entry point for the thread and you will put you complete business logic inside
this method. Following is simple syntax of run() method:
public void run( )
Step 2:
➢ At second step you will instantiate a Thread object using the following constructor:
Thread(Runnable threadObj, String threadName);
➢ Where, threadObj is an instance of a class that implements the Runnable interface and
threadName is the name given to the new thread.
Step 3
➢ Once Thread object is created, you can start it by calling start( ) method, which executes a call
to run( ) method. Following is simple syntax of start() method:
void start( );
Example:
Here is an example that creates a new thread and starts it running:
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--)
{
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 79


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public class TestThread {


public static void main(String args[])
{
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}

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:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 80


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 81


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 83


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

public final void wait()throws


It waits until object is notified.
InterruptedException

public final void wait(long


It waits for the specified amount of time
timeout)throws InterruptedException

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()

Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:


ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 84
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases
the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the object.

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.
wait() sleep()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

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.,

final Customer c=new Customer();


new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();

}}
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");
}
}
}
};

// t2 tries to lock resource2 then resource1


Thread t2 = new Thread() {

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 86


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public void run() {


synchronized (resource2) {
System.out.println("Thread 2: locked resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
} }
Output:
Thread 1: locked resource 1
Thread 2: locked resource 2

More Complicated Deadlocks


➢ A deadlock may also include more than two threads. The reason is that it can be difficult to
detect a deadlock. Here is an example in which four threads have deadlocked:
Thread 1 locks A, waits for B
Thread 2 locks B, waits for C
Thread 3 locks C, waits for D
Thread 4 locks D, waits for A
Thread 1 waits for thread 2, thread 2 waits for thread 3, thread 3 waits for thread 4, and thread
4 waits for thread 1.

How to avoid deadlock?


➢ A solution for a problem is found at its roots. In deadlock it is the pattern of accessing the
resources A and B, is the main issue. To solve the issue we will have to simply re-order the
statements where the code is accessing shared resources.

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) {

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 87


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

System.out.println("In block 1");


}
}
}
};
// Thread-2
Runnable b2 = new Runnable() {
public void run() {
synchronized (b) {
// Thread-2 have resource2 but need resource1 also
synchronized (a) {
System.out.println("In block 2");
}
}
} };
new Thread(b1).start();
new Thread(b2).start();
}
// resource1
private class resource1 {
private int i = 10;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
// resource2
private class resource2 {
private int i = 20;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
}
Output:
In block 1
In block 2
➢ In the above code, class DeadlockSolved solves the deadlock kind of situation. It will help in
avoiding deadlocks, and if encountered, in resolving them.
➢ Deadlocks cannot be completely resolved. But we can avoid them by following basic rules
mentioned below:
1. Avoid Nested Locks: We must avoid giving locks to multiple threads, this is the main reason
for a deadlock condition. It normally happens when you give locks to multiple threads.
2. Avoid Unnecessary Locks: The locks should be given to the important threads. Giving locks
to the unnecessary threads that cause the deadlock condition.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 88


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

MANAGING INPUTS/ OUTPUTS STREAMS:


➢ Java I/O (Input and Output) is used to process the input and produce the output.
➢ Java uses the concept of a stream to make I/O operation fast. The java.io package contains all
the classes required for input and output operations.
➢ We can perform file handling in Java by Java I/O API.

What is File I/O?


➢ Java I/O stream is the flow of data that you can either read from, or you can write to.
It is used to perform read and write operations in file permanently.
➢ Java uses streams to perform these tasks. Java I/O stream is also called File Handling, or File
I/O. It is available in java.io package.

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 89


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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;

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 90


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

while ((c = in.read()) != -1)


{
out.write(c);
}
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
} }
}
}

Byte Input Stream:


➢ These are used to read byte data from various input devices.
➢ InputStream is an abstract class and it is the super class of all the input byte streams.
List of Byte Input Streams:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 91


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Byte Input Stream Methods:

Byte Output Stream:


➢ These are used to write byte data to various output devices.
➢ Output Stream is an abstract class and it is the superclass for all the output byte streams.
List of Byte Output Streams:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 92


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Java Byte Array Output Stream class methods

Example of Java ByteArrayOutputStream


Let's see a simple example of java ByteArrayOutputStream class to write common data into 2
files: f1.txt and f2.txt.

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...

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 93


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

f1.txt:
A
f2.txt:
A

Character Streams Classes:


➢ Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode.
➢ Though there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
➢ We can re-write the above example, which makes the use of these two classes to copy an input
file (having unicode characters) into an output file −
Example
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;
try
{
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 94


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Character Input Stream:


➢ These are used to read char data from various input devices.
➢ Reader is an abstract class and is the super class for all the character input streams.

List of Character Input Streams:

Example to read contents of file:


import java.io.*;
class ReadHello
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream(“hello.txt”);
int i=0;
while((i=fin.read())!=-1)
{
System.out.println((char)i);
}
fin.close();
}
catch(Exception e)
{
system.out.println(e);
}
}}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 95


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

Character Output Stream:


➢ These are used to write char data to various output devices.
➢ Writer is an abstract class and is the super class of all the character output streams.

List of Character Output Stream:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 96


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example to write in a file:


Example 1:
import java.io.*;
public class Intellipaat
{
public static void main(String args[])
{
try
{
FileOutputstream fo=new FileOutputStream(“hello.txt”);
String i=”Hello Intellipaat “;
byte b[]=i.getBytes();/ /converting string into byte array
fo.write(i);
fo.close();
}
catch(Exception e)
{
system.out.println(e);}
}
}
This will create a file hello.txt
Output:
Hello Intellipaat

1. READING INPUT FROM CONSOLE


➢ By default, to read from system console, we can use the Console class. This class provides
methods to access the character-based console, if any, associated with the current Java process.
To get access to Console, call the method System.console().
➢ Console gives three ways to read the input:
✓ String readLine() – reads a single line of text from the console.
✓ char[ ] readPassword() – reads a password or encrypted text from the console with echoing
disabled
✓ Reader reader() – retrieves the Reader object associated with this console. This reader is
supposed to be used by sophisticated applications. For example, Scanner object which utilizes
the rich parsing/scanning functionality on top of the underlying Reader.
1.1. Reading Input with readLine()
Console console = System.console();
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
}
String userName = console.readLine("Enter the username: ");
System.out.println("Entered username: " + userName);
Output
Enter the username: Ranjith
Entered username: Ranjith

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 97


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

1.2. Reading Input with readPassword()


Console console = System.console();
if(console == null) {
System.out.println("Console is not available to current JVM process");
return;
}
char[ ] password = console.readPassword("Enter the password: ");
System.out.println("Entered password: " + new String(password));

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

2. WRITING OUTPUT TO CONSOLE


➢ The easiest way to write the output data to console is System.out.println() statements. Still, we
can use printf() methods to write formatted text to console.
2.1. Writing with System.out.println
System.out.println("Hello, world!");
Output
Hello, world!
2.2. Writing with printf()
➢ The printf(String format, Object... args) method takes an output string and multiple parameters
which are substituted in the given string to produce the formatted output content. This
formatted output is written in the console.
String name = "Rajesh";

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 98


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

int age = 38;


console.printf("My name is %s and my age is %d", name, age);
Output:
My name is Rajesh and my age is 38
FILE HANDLING:
➢ The File class is an abstract representation of file and directory pathname. A pathname can be
either absolute or relative.
➢ The File class have several methods for working with directories and files such as creating new
directories or files, deleting and renaming directories or files, listing the contents of a directory
etc.
Creating a File:
import java.io.*;
public class FileDemo
{
public static void main(String[] args)
{
try
{
File file = new File("javaFile123.txt");
if (file.createNewFile())
{
System.out.println("New File is created!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e)
{
e.printStackTrace();
} } }
Output:
New File is created!
Opening a File in Java:
import java.io.*;
import java.util.Scanner;
public class OpenFileExample2
{
public static void main(String args[])
{
try
{
//constructor of file class having file as argument
File file=new File("C:\\demo\\demofile.txt");
FileInputStream fis=new FileInputStream(file); //opens a connection to an actual file
System.out.println("file content: ");
int r=0;

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 99


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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();
}}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 100


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Reading and Writing Files:


As described earlier, a stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.

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.

Sr.No. Method & Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources associated with
the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method of this file
output stream is called when there are no more references to this stream. Throws an
IOException.

3 public int read(int r)throws IOException{}


This method reads the specified byte of data from the InputStream. Returns an int. Returns
the next byte of data and -1 will be returned if it's the end of the file.

4 public int read(byte[] r) throws IOException{}


This method reads r.length bytes from the input stream into an array. Returns the total
number of bytes read. If it is the end of the file, -1 will be returned.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 101


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

5 public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream. Returns an int.
There are other important input streams available, for more detail you can refer to the following links
➢ ByteArrayInputStream
➢ DataInputStream
FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would create a file,
if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the file −
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First, we
create a file object using File() method as follows −
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
Once you have OutputStream object in hand, then there is a list of helper methods, which can be used
to write to stream or to do other operations on the stream.
Sr.No. Method & Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources associated with
the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close method of this file
output stream is called when there are no more references to this stream. Throws an
IOException.

3 public void write(int w)throws IOException{}


This methods writes the specified byte to the output stream.

4 public void write(byte[] w)


Writes w.length bytes from the mentioned byte array to the OutputStream.
There are other important output streams available, for more detail you can refer to the following links
➢ ByteArrayOutputStream
➢ DataOutputStream

Following is the example to demonstrate InputStream and OutputStream –


import java.io.*;
public class fileStreamTest
{
public static void main(String args[])
{
try
{
byte bWrite [] = {11,21,3,40,5};

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 102


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

OutputStream os = new FileOutputStream("test.txt");


for(int x = 0; x < bWrite.length ; x++)
{
os.write( bWrite[x] ); // writes the bytes
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(int i = 0; i < size; i++)
{
System.out.print((char)is.read() + " ");
}
is.close();
}
catch (IOException e)
{
System.out.print("Exception");
}
}
}
The above code would create file test.txt and would write given numbers in binary format. Same
would be the output on the stdout screen.
IO Exceptions:
➢ IOExceptions are thrown when there is any input / output file operation issues while
application performing certain tasks accessing the files. IOException is a checked
exception and application developer has to handle in correct way.
➢ IOException has many sub classes that are specific in nature. That means, when your
application searching to read a file, if the file is not found that there is a ileNotFoundException
to be thrown. FileNotFoundException is a subclass of IOException.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ExceptionExample
{
public FileInputStream testMethod1(){
File file = new File("test.txt");
FileInputStream fileInputStream = null;
try
{
fileInputStream = new FileInputStream(file);
fileInputStream.read();
}

catch (IOException e)
{
e.printStackTrace();
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 103


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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();
}
}

COPYING BYTES FROM ONE FILE TO ANOTHER


➢ We can copy a file from one location to another using FileInputStream and FileOutputStream
classes in Java.
➢ For this we have to import some specific classes of java.io package. So for instance let us
include the entire package with statement import java.io.*;
➢ The main logic of copying file is to read the file associated to FileInputStream variable and
write the read contents into the file associated with FileOutputStream variable.
Methods used in the program
1. int read(); Reads a byte of data. Present in FileInputStream. Other versions of this method : int
read(byte[] bytearray) and int read(byte[] bytearray, int offset, int length)
2. void write(int b) : Writes a byte of data. Present in FileOutputStream. Other versions of this
method : void write(byte[] bytearray) and void write(byte[] bytearray, int offset, int length);
import java.io.*;
class CopyBytes
{
publicstaticvoid main(String[] args)
{
FileInputStream fis = null;
FileOutputStream fos = null;
try
{
fis = new FileInputStream("input.txt");
fos = new FileOutputStream("output.txt");
int ch;
while((ch=fis.read())!=1)
{
fos.write(ch);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 104


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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();
} }

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 105


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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();
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 106


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

AWT (ABSTRACT WINDOW TOOLKIT):


➢ AWT represents a class library to develop applications using GUI. The java.awt package
consists of classes and interfaces to develop GUIs.

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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 107


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 108


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 109


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

AWT Button Control


➢ The most widely used control is Button. A button is a component that contains a label and that
generates an event when it is pressed.
Creating Button : Button b = new Button(String label);
Button Constructors:
1. Button() throws HeadlessException: It creates an empty button.
2. Button(String str) throws HeadlessException: It creates a button that contains str as a
label.
Button Methods :
1. void setLabel(String str): You can set its label by calling setLabel(). Here, str is the
new Label for the button.
2. String getLabel(): You can retrieve its label by calling getLabel() method.
Example
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo extends Frame
{
Button b1, b2;
ButtonDemo ()
{
b1 = new Button ("OK");
b2 = new Button ("CANCEL");
this.setLayout (null);
b1.setBounds (100, 100, 80, 40);;
b2.setBounds (200, 100, 80, 40);
this.add (b1);
this.add (b2);
this.setVisible (true);
this.setSize (300, 300);
this.setTitle ("button");
this.addWindowListener (new WindowAdapter ()
{
public void windowClosing (WindowEvent we)
{
System.exit (0);
}
});
}
public static void main (String args[])
{
new ButtonDemo ();
}
}
Output:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 110


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

AWT TextComponent Control


➢ The TextComponent class is the superclass of any component that permits the editing of some
text. A text component embodies a string of text.
➢ The TextComponent class defines a group of methods that determine whether or not this text is
editable.
➢ There are two types of TextComponent:
1. TextField
2. TextArea
AWT TextField Control
➢ The TextField component will allow the user to enter some text. It is used to implement a
single-line text-entry area, usually called an edit control.
➢ It also allows the user to enter strings and edit the text using the arrow keys, cut and paste keys,
and mouse selections. TextField is a subclass of TextComponent.
Creating TextField : TextFielf tf = new TextField(size);
TextField Constructors
1. TextField() throws HeadlessException: It creates a default textfield.
2. TextField(int numChars) throws HeadlessException: It creates a text field that is
numChars characters wide.
3. TextField(String str) throws HeadlessException: It initializes the text field with the
string contained in str.
4. TextField(String str, int numChars) throws HeadlessException: It initializes a text
field and sets its width.
TextField Methods
1. String getText(): It is used to obtain the string currently contained in the text field.
2. void setText(String str): It is used to set the text. Here, str is the new String.
3. void select(int startIndex, int endIndex): It is used to select a portion of the text under
program control. It selects the characters beginning at startIndex and ending at
endIndex-1.
4. String getSelectedText(): It returns the currently selected text.
5. boolean isEditable(): It is used to determine editability. It returns true if the text may
be changed and false if not.
6. void setEditable(boolean canEdit): It is used to control whether the contents of a text
field may be modified by the user. If canEdit is true, the text may be changed. If it is
false, the text cannot be altered.
7. void setEchoChar(char ch): It is used to disable the echoing of the characters as they
are typed. This method specifies a single character that TextField will display when
characters are entered.
8. boolean echoCharIsSet(): By this method, you can check a text field to see if it is in
this mode.
9. char getEchochar(): It is used to retrieve the echo character.
Example
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="TextFieldDemo" width=380 height=150> </applet>
*/
public class TextfieldDemo extends Applet implements ActionListener
{
TextField name, pass;

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 111


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public void init ()


{
Label namep = new Label ("Name: ", Label.RIGHT);
Label passp = new Label ("Password: ", Label.RIGHT);
name = new TextField (12);
pass = new TextField (8);
pass.setEchoChar ('?');
add (namep);
add (name);
add (passp);
add (pass);
//register to receive action events
name.addActionListener (this);
pass.addActionListener (this);
}
//User pressed Enter.
public void actionPerformed (ActionEvent ae)
{
repaint ();
}
public void paint (Graphics g)
{
g.drawString ("Name: " + name.getText (), 6, 60);
g.drawString ("Selected text in name: " + name.getSelectedText (), 6, 80);
g.drawString ("Password: " + pass.getText (), 6, 100);
}
}
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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 112


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

4. TextArea(String str, int numLines, int numChars) throws HeadlessException: It


initializes a text field and sets its width. Initial text can be specified by str.
5. TextArea(String str, int numLines, int numChars, int sBars) throws
HeadlessException: Here, you can specify the scroll bars that you want the control to
have. sBars must be one of these values :
1. SCROLLBARS_BOTH
2. SCROLLBARS_NONE
3. SCROLLBARS_HORIZONTAL_ONLY
4. SCROLLBARS_VERTICAL_ONLY
TextArea Methods
➢ TextArea is a subclass of TextComponent. Therefore, it supports the getText( ),
setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described in
the TextField section. TextArea adds the following methods:
1. void append(String str): It appends the string specified by str to the end of the current
text.
2. void insert(String str, int index): It inserts the string passed in str at the specified
index.
3. voidReplaceRange(String str, int startIndex, int endIndex): It is used to replace the
text. It replaces the characters from startIndex to endIndex-1.
Example
import java.awt.*;
import java.applet.*; /* <applet code="TextAreaDemo" width=300 height=250> </applet> */
public class TextAreaDemo extends Applet {
public void init() {
String val = "Java SE 6 is the latest version of the most\n"
+ "widely-used computer language for Internet programming.\n"
+ "Building on a rich heritage, Java has advanced both\n"
+ "the art and science of computer language design.\n\n"
+ "One of the reasons for Java's ongoing success is its\n"
+ "constant, steady rate of evolution. Java has never stood\n"
+ "still. Instead, Java has consistently adapted to the\n"
+ "rapidly changing landscape of the networked world.\n"
+ "Moreover, Java has often led the way, charting the\n" + "course for others to follow.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}
Output

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 113


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

AWT Checkbox Control


➢ A checkbox may be a control that’s used to turn an option on or off. It consists of a little box
that will either contain a check or not.
➢ There’s a label related to each checkbox that describes what option the box represents. You
modify the state of a checkbox by clicking on.
➢ Checkboxes are often used individually or as a part of a gaggle.
➢ Checkboxes are objects of the Checkbox class.
Creating Checkbox : Checkbox cb = new Checkbox(Label);
Checkbox Constructor
1. Checkbox() throws HeadlessException: Creates a checkbox whose label is initially
blank. The state of the checkbox is unchecked.
2. Checkbox(String str) throws HeadlessException: Creates a checkbox whose label is
specified by str. The state of the checkbox is unchecked.
3. Checkbox(String str, Boolean on) throws HeadlessException: It allows you to line
the initial state of the checkbox. If one is true, the checkbox is initially checked;
otherwise, it’s cleared.
4. Checkbox(String str, Boolean on, CheckboxGroup cbGroup) throws
HeadlessException or Checkbox(String str, CheckboxGroup cbGroup, Boolean
on) throws HeadlessException: It creates a checkbox whose label is specified by str
and whose group is specified by cbGroup. If this checkbox isn’t a part of a gaggle, then
cbGroup must be null. the worth of on determines the initial state of the checkbox.
Methods of Checkbox
1. boolean getState(): To retrieve the present state of a checkbox.
2. void setState(boolean on): To line its state, call setState(). Here, if one is true, the box
is checked. If it’s false, the box is cleared.
3. String getLabel(): you’ll obtain the present label related to a checkbox by calling
getLabel().
4. void setLabel(String str): To line the label, call setLabel(). The string passed in str
becomes the new label related to the invoking checkbox.
Example
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="CheckboxDemo" width=250 height=200> </applet> */
public class CheckboxDemo extends Applet implements ItemListener
{
String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init ()
{
winXP = new Checkbox ("Windows XP", null, true);
winVista = new Checkbox ("Windows Vista");
solaris = new Checkbox ("Solaris");
mac = new Checkbox ("Mac OS");
add (winXP);
add (winVista);
add (solaris);
add (mac);
winXP.addItemListener (this);

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 114


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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: Radio Buttons


➢ It is possible to make a group of mutually exclusive checkboxes during which one and just one
checkbox up the group are often checked at anybody time.
➢ These checkboxes are often called radio buttons because they act just like the station selector
on a car radio, only one station is often selected at anybody’s time.
➢ To create a group of mutually exclusive checkboxes, you want to first define the group to
which they’re going to belong then specify that group once you construct the checkboxes.
➢ Checkbox groups are objects of the type CheckboxGroup.
➢ Only the default constructor is defined, which creates an empty group.
Creating Radiobutton :
CheckboxGroup cbg = new CheckboxGroup();
Checkbox rb = new Checkbox(Label, cbg, boolean);

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 115


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 116


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:

AWT Choice Control


➢ This component will display a group of times as a drop-down menu from which a user can
select only one item.
➢ The choice component is used to create a pop-up list of items from which the user may choose.
Therefore, Choice control is a form of a menu.
➢ When it is inactive, a Choice component takes up only enough space to show the currently
selected item. When the user clicks on a Choice component, the whole list of choices pops up,
and a new selection can be made.
Note: Choice only defines the default constructor, which creates an empty list.
Creating Choice : Choice ch = new Choice();
Choice Methods
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.
2. String getSelectedItem(): It determines which item is currently selected. It returns a
string containing the name of the item.
3. int getSelectedIndex(): It determines which item is currently selected. It returns the
index of the item.
4. int getItemCount(): It obtains the number of items in the list.
5. void select(int index): It is used to set the currently selected item with a zero-based
integer index.
6. void select(String name): It is used to set the currently selected item with a string that
will match a name in the list.
7. 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="ChoiceDemo" width=300 height=180> </applet> */
public class ChoiceDemo extends Applet implements ItemListener
{
Choice os, browser;
String msg = "";
public void init ()
{
os = new Choice ();
browser = new Choice ();
// add items to os list
os.add ("Windows XP");
os.add ("Windows Vista");
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 117
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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:

AWT List Control :


➢ This component will display a group of items as a drop-down menu from which a user can
select only one item.
➢ The List class provides a compact, multiple-choice, scrolling selection list.
➢ Unlike the selection object, which shows only the only selected item within the menu, an
inventory object is often constructed to point out any number of choices within the visible
window. It also can be created to permit multiple selections.
Creating List : List l = new List(int, Boolean);

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 118


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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");

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 119


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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:

AWT Scroll Bar Control


➢ Scrollbars are used to select continuous values between a specified minimum and maximum.
Scroll bars may be oriented horizontally or vertically.
➢ A scroll bar is really a composite of several individual parts. Each end has an arrow that you
simply can click to get the present value of the scroll bar one unit within the direction of the
arrow.
➢ The current value of the scroll bar relative to its minimum and maximum values are indicated
by the slider box for the scroll bar. Scrollbars are encapsulated by the Scrollbar class.
Creating Scrollbar : Scrollbar sb = new Scrollbar();

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 120


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 121


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public void mouseDragged (MouseEvent me)


{
int x = me.getX ();
int y = me.getY ();
vertSB.setValue (y);
horzSB.setValue (x);
repaint ();
}
//Necessary for MouseMotionListener
public void mouseMoved (MouseEvent me)
{
}
//Display current value of scroll bars.
public void paint (Graphics g)
{
msg = "Vertical: " + vertSB.getValue ();
msg += ", Horizontal: " + horzSB.getValue ();
g.drawString (msg, 6, 160);
//show current mouse drag position
g.drawString ("*", horzSB.getValue (), vertSB.getValue ());
}
}
Output

Java AWT Panel


➢ The Panel is a simplest container class. It provides space in which an application can attach any
other component. It inherits the Container class.
➢ It doesn't have title bar.
AWT Panel class declaration
1. public class Panel extends Container implements Accessible
Example:
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 122
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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:

AWT MenuItem and Menu


➢ The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu must belong to the MenuItem or any of its subclass.
➢ The object of Menu class is a pull down menu component which is displayed on the menu bar.
It inherits the MenuItem class.
AWT MenuItem class declaration
1. public class MenuItem extends MenuComponent implements Accessible

AWT Menu class declaration


1. public class Menu extends MenuItem implements MenuContainer, Accessible

AWT MenuItem and Menu Example


import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 123


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

MenuItem i2=new MenuItem("Item 2");


MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
Output:

Working with Frame Windows:

➢ 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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 124


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ Its signature is shown below:


void setSize(int newWidth, int newHeight)
void setSize(Dimension newSize)
➢ The new size of the window is specified by ̳newWidth‘ and ̳newHeight‘, or by the ̳width‘ and
̳height‘ fields of the Dimension object passed in ̳newSize‘. The dimensions are specified in
terms of pixels.
➢ The getSize( ) method is used to obtain the current size of a window. Its signature is:
Dimension getSize( )
➢ This method returns the current size of the window contained within the ̳width‘ and ̳height‘
fields of a Dimension object.
Hiding and showing a Window
➢ After a frame window has been created, it will not be visible until we call setVisible( ). Its
signature is:
void setVisible(boolean visibleFlag)
➢ The component is visible if the argument to this method is true. Otherwise, it is hidden.
Setting a Windows Title We can change the title in a frame window using setTitle( ), which
has this general form:
void setTitle(String newTitle)
➢ Here, ̳newTitle‘ is the new title for the window. Closing a Frame Window When using a
frame window, our program must remove that window from the screen when it is closed,
by calling setVisible(false).
➢ To intercept a window- close event, we must implement the windowClosing( ) method of
the WindowListener interface. Inside windowClosing( ), we must remove the window from
the screen.
Creating a Frame Window in an Applet
➢ The following applet creates a subclass of Frame called SampleFrame. A window of
this subclass is instantiated within the init( ) method of AppletFram .
➢ Note that ̳SampleFrame‘ calls Frame‘s constructor. This causes a standard frame
window to be created with the title passed in title.
➢ This example overrides the applet window‘s start( ) and stop( ) method s so that they
show and hide the child window, respectively. It also causes the child window to be
shown when the browser returns to the applet.
/*
<applet code="AppletFrame" width=300 height=50>
</applet>
*/
class SampleFrame extends Frame
{
SampleFrame(String title)
{
super(title);
}
public void paint(Graphics g)
{
g.drawString("This is in frame window", 10, 40);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 125


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ public class AppletFrame extends Applet


{
Frame f;
public void init()
{
f = new SampleFrame("A Frame Window");
f.setSize(250, 250);
f.setVisible(true);
}
public void start()
{
f.setVisible(true);
} public void stop()
{
f.setVisible(false);
}
public void paint(Graphics g)
{
g.drawString("This is in applet window", 10, 20);
}
}
Output:

Working with Graphics


Working with Color
➢ Java supports color in a portable, device-independent fashion. The AWT color system allows
us to specify any color that we want.
➢ It then finds the best match for that color, given the limits of the display hardware currently
executing our program or applet.
➢ Thus, our code does not need to be concerned with the differences in the way color is
supported by various hardware devices. Color is encapsulated by the Color class.
Constructors:
Color(int red, int green, int blue)
Color(int rgbValue)
Color(float red, float green, float blue)

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 126


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ 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);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 127


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Working with Fonts


➢ The AWT supports multiple type fonts. It provides flexibility by abstracting font-manipulation
operations and allowing for dynamic selection of fonts. In Java, fonts have a family name, a
logical font name, and a face name.
➢ The family name is the general name of the font, such as Courier. The logical name specifies a
category of font, such as Monospaced. The face name specifies a specific font, such as Courier
Italic. Fonts are encapsulated by the Font class. Several of the methods defined by Font are
listed below.
The Font class defines these variables:
Variable Meaning
String name Name of the font
float pointSize Size of the font in points
int size Size of the font in points
int style Font style
Method Description
static Font decode(String str) Returns a font given its name.
boolean equals(Object FontObj) Returns true if the invoking object contains the same font
as that specified by FontObj. Otherwise, it returns false.
String getFamily( ) Returns the name of the font family to
which the invoking font belongs. staticFontgetFont(Stringproperty) Returns the font associated
with the system property specified by property. Null is
returned if property does not exist.
staticFontgetFont(Stringproperty, defaultFont) Returns the font associated with the system
Font property specified by property. The font specified
by
default Font is returned if property does not exist.
String getFontName() Returns the face name of the invoking font.
String getName( ) Returns the logical name of the invoking font.
int getSize( ) Returns the size, in points, of the invoking font.
int getStyle( ) Returns the style values of the invoking font.
int hashCode( ) Returns the hash code associated with the invoking
object.
boolean isBold( ) Returns true if the font includes the BOLD style value.
Otherwise, false is returned.
boolean isItalic( ) Returns true if the font includes the ITALIC style value.
Otherwise, false is returned.
boolean isPlain( ) Returns true if the font includes the PLAIN style value.
Otherwise, false is returned.
String toString( ) Returns the string equivalent of the invoking font.
Here is an applet that shows how to obtain the names of the available
font families:
/*
<applet code="ShowFonts" width=550 height=60>
</applet>
*/
import java.applet.*;
import java.awt.*;

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 128


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public class ShowFonts extends Applet


{
public void paint(Graphics g)
{
String msg = "";
String FontList[];
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
FontList = ge.getAvailableFontFamilyNames();
for(int i = 0; i < FontList.length; i++)
msg += FontList[i] + " ";
g.drawString(msg, 4, 16);
}
}
Creating and Selecting a Font
Component. It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font.
// Displaying different fonts
import java.awt.Font;
import java.awt.Graphics;
import java.applet.Applet;
/*
<applet code="Fonts" width=300 height=150>
</applet>
*/
public class Fonts extends Applet
{
public void paint(Graphics g)
{
Font f1 = new Font("TimesRoman", Font.PLAIN, 18);
Font f2 = new Font("Courier", Font.BOLD, 16);
Font f3 = new Font("Arial", Font.ITALIC, 20);
Font f4 = new Font("Times", Font.BOLD + Font.ITALIC,
22);
g.setFont(f1);
g.drawString("Times Roman plain font: 18", 10, 30);
g.setFont(f2);
g.drawString("Courier bold font: 16", 10, 60);
g.setFont(f3);
g.drawString("Arial italic font: 20", 10, 80);
g.setFont(f4);
g.drawString("Times bold italic font: 22", 10, 120);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 129


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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>
*/

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 130


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public class FlowLayoutDemo extends Applet implements ItemListener


{
String msg="";
Checkbox m,f;
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT));
m = new Checkbox("Male", true);
f = new Checkbox("Female");
add(m );
add(f);
m.addItemListener(this);
f.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 = " Male: " + m.getState();
g.drawString(msg, 6, 100);
msg = " Female: " + f.getState();
g.drawString(msg, 6, 150);
}
}

(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);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 131


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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);

}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 132


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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>
*/

public class GridLayoutDemo2 extends Applet


{
Button
b1,b2,b3,b4;
public void init()
{
setLayout(new GridLayout(2, 2));
b1=new Button("PVP");
b2=new Button("BEC");
b3=new Button("VRSEC");
b4=new Button("RVR&JC");
add(b1);
add(b2);
add(b3);
add(b4);
}
}
or
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200>
</applet>
*/

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 133


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public class GridLayoutDemo extends Applet


{
static final int n = 4;
public void init() {
setLayout(new GridLayout(n, n));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++)
{
int k = i * n +
j;if(k > 0)
add(new Button("" + k));
}
}
}
}
CardLayout:
➢ A CardLayout object is a layout manager which treats each component as a card.
Only one card is displayed at a time, and the container acts as a stack of cards. The
first component added to a CardLayout object is visible component when the
container is first displayed.
CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
➢ The first form creates a default card layout. The second form allows you to specify
the horizontal and vertical space left between components in horz and vert,
respectively.
➢ Use of a card layout requires a bit more work than the other layouts. The cards are typically
held in an object of type Panel. This panel must have CardLayout selected as its layout
manager. Finally, you add this pane to the window.
➢ Once these steps are complete, you must provide some way for the user to select between
cards. One common approach is to include one push button for each card in the deck. When
card panels are added to a panel, they are usually given a name. Thus, most of the time, you
will use this form of add( ) when adding cards to a panel:
void add(Component panelObj, Object name)
or
void add(Object name, Component panelObj)
➢ Here, name is a string that specifies the name of the card whose panel is specified by
panelObj. After you have created a deck, your program activates a card by calling one of the
following methods defined by CardLayout:
void first(Container deck)
void last(Container deck)
void next(Container
deck)
void previous(Container deck)
void show(Container deck, String cardName)

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 134


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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();

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 135


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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>
*/

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 136


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public class GridBagDemo extends Applet


{
Button b1,b2,b3,b4,b5,b6,b7,b8 ;
public void init() {
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();setLayout(gbag);
// Define check boxes. b1=new Button("Button 1");
b2=new Button("Button 2");
b3=new Button("Button 3");
b4=new Button("Button 4");
b5=new Button("Button 5");
b6=new Button("Button 6");
b7=new Button("Button 7");
b8=new Button("Button 8");
gbc.gridx=0;
gbc.gridy=0;
gbag.setConstraints(b1,gbc);
gbc.gridx=1;
gbc.gridy=0;
gbag.setConstraints(b2,gbc);
gbc.gridx=2;
gbc.gridy=0;
gbag.setConstraints(b3,gbc);
gbc.gridx=0;
gbc.gridy=1;
gbag.setConstraints(b4,gbc);
gbc.gridx=1;
gbc.gridy=1;
gbc.gridwidth=2;
gbc.gridheight=2;
gbc.ipady=25;
gbc.ipadx=20;
gbc.fill=GridBagConstraints.BOTH;
gbag.setConstraints(b5,gbc);
gbc.gridx=0;
gbc.gridy=2;
gbc.anchor=GridBagConstraints.WEST;
gbc.ipady= 0;
gbc.ipadx= 0;
gbc.fill=GridBagConstraints.NONE;
gbag.setConstraints(b7,gbc); add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b7);

}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 137


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

Delegation Event Model:


➢ The modern approach (from version 1.1 onwards) to handle events is based on the
delegation event model. Its concept is quite simple: a source generates an event and
sends itto one or more listeners.

➢ 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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 138


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Sources of Events:

Event Source Description


Button Generates action events when the button is pressed.
Check box Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked;
Generates action events when a menu item is selected; generates item
Menu item events when a checkable menu item is selected or deselected.
Scroll bar Generates adjustment events when the scroll bar is manipulated.
Text components Generates text events when the user enters a character.
Generates window events when a window is activated, closed,
Window deactivated, deiconified, iconified, opened, or quit.
Event Classes and Listener Interfaces:

➢ 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.,

MouseEvent moved, clicked, pressed, or released; MouseListener and


also generated when the mouse enters or MouseMotionListener
exits a component.
Generated when the value of a text area or
TextEvent text field is changed. TextListener
Generated when a window is activated,
WindowEvent closed, deactivated, deiconified, iconified, WindowListener
opened, or quit.
Useful Methods of Component class:

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.

The ActionEvent Class:


➢ An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a
menu item is selected.
➢ The ActionEvent class defines four integer constants that can be used to identify any
modifiers associated with an action event: ALT_MASK, CTRL_MASK,
META_MASK (Ex.Escape) , and SHIFT_MASK.
ActionEvent has these three constructors:
o ActionEvent(Object src, int type, String cmd)
o ActionEvent(Object src, int type, String cmd, int modifiers)
o ActionEvent(Object src, int type, String cmd, long when, int modifiers)
You can obtain the command name for the invoking ActionEvent object by using the
getActionCommand( ) method, shown here:
String getActionCommand( )

The AdjustmentEvent Class:


An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.
The user clicked inside the scroll bar to decrease its
BLOCK_DECREMENT value.
The user clicked inside the scroll bar to increase its
BLOCK_INCREMENT value.
TRACK The slider was dragged.
The button at the end of the scroll bar was clicked to
UNIT_DECREMENT
decrease its value.
The button at the end of the scroll bar was clicked to
UNIT_INCREMENT
increase its value.
The ComponentEvent Class:
➢ A ComponentEvent is generated when the size, position, or visibility of a componentis
changed. There are four types of component events. The ComponentEvent class defines integer
constants that can be used to identify them:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 140


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

COMPONENT_HIDDEN The component was hidden.


COMPONENT_MOVED The component was moved.
COMPONENT_RESIZED The component was resized.
COMPONENT_SHOWN The component became visible.
➢ ComponentEvent is the superclass either directly or indirectly of ContainerEvent,
FocusEvent, KeyEvent, MouseEvent, and WindowEvent, among others.
➢ The getComponent( ) method returns the component that generated the event.
➢ It isshown here:
Component getComponent( )

The ContainerEvent Class:


➢ A ContainerEvent is generated when a component is added to or removed from acontainer.
There are two types of container events. The ContainerEvent class defines constants that
can be used to identify them: COMPONENT_ADDED and COMPONENT_REMOVED.
The FocusEvent Class:
➢ A
FocusEvent is generated when a component gains or loses input focus. Theseevents
are identified by the integer constants FOCUS_GAINED and FOCUS_LOST.
The InputEvent Class:
➢ The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for
component input events. Its subclasses are KeyEvent and MouseEvent.
➢ InputEvent defines several integer constants that represent any modifiers, such as the
control key being pressed, that might be associated with the event. Originally, the
InputEvent class defined the following eight values to represent the modifiers:

ALT_MASK ALT_GRAPH_M BUTTON2_MASK BUTTON3_MASK


ASK
BUTTON1_MASK CTRL_MASK META_MASK SHIFT_MASK

➢ 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:

ALT_DOWN_MASK ALT_GRAPH_DOWN_MASK BUTTON1_DOWN_MAS


K
BUTTON2_DOWN_MASK BUTTON3_DOWN_MASK CTRL_DOWN_MASK

META_DOWN_MASK SHIFT_DOWN_MASK

The KeyEvent Class


➢ A KeyEvent is generated when keyboard input occurs. There are three types of key events,
which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and
KEY_TYPED.
ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 141
23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

➢ 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.

The MouseEvent Class:


➢ There are eight types of mouse events. The MouseEvent class defines the followinginteger
constants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse
MOUSE_DRAGGED The user dragged the mouse
MOUSE_ENTERED The mouse entered a component
MOUSE_EXITED The mouse exited from a
component.
MOUSE_MOVED The mouse moved
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved.
➢ Two commonly used methods in this class are getX( ) and getY( ). These return the Xand Y
coordinates of the mouse within the component when the event occurred. Their forms are
shown here:
int getX( )
int getY( )
The TextEvent Class:
➢ Instances
of this class describe text events. These are generated by text fields and text areas when
characters are entered by a user or program. TextEvent defines the integer constant
TEXT_VALUE_CHANGED.
The WindowEvent Class:
➢ The WindowEvent class defines integer constants that can be used to identifydifferent
types of events:

WINDOW_ACTIVATED The window was activated.


WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed.
WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window was iconified.
WINDOW_ICONIFIED The window gained input focus.
WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.

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:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 142


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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)

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 143


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

This interface defines two methods. When a component obtains


keyboard focus, focusGained( ) is invoked. When a component
FocusListener loses keyboard focus, focusLost( ) is called. Their general forms
are shown here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
This interface defines three methods.
KeyListener void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)

Steps to perform Event Handling


Following steps are required to perform event handling:
1. Register the component with the Listener
2. Implement the concerned interface
Registration Methods:
➢ For registering the component with the Listener, many classes provide the registration
methods. For example:

Handling Mouse Events Example Program:


// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*; /*
<applet code="MouseEvents" width=300height=100> </applet>
*/
public class MouseEvents extends Applet implements MouseListener, MouseMotionListener
{
String msg = "";

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 144


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

int mouseX = 0, mouseY = 0; // coordinates of


mousepublic void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
// Handle mouse clicked
public void mouseClicked(MouseEvent me)
{
// save
coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse clicked.";
repaint();
}
// Handle mouse entered.
public void mouseEntered(MouseEvent me)
{
// save
coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint( );
}
// Handle mouse exited.
public void mouseExited(MouseEvent me)
{
// save
coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse exited.";
repaint( );
}
// Handle button pressed.
public void mousePressed(MouseEvent me)
{
// save coordinates
mouseX = me.getX( );
mouseY = me.getY( );
msg = "Down";
repaint( );
}
// Handle button released.
public void mouseReleased(MouseEvent me)
{

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 145


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

// 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:

Handling Key Board Events:


// Demonstrate the key event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*; /*

<applet code="SampleKey" width=300 height=100>


</applet>
*/

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 146


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public class SampleKey extends Applet implements KeyListener


{
String msg = "";

public void init( )


{
addKeyListener(this);
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down"); }
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar(); repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, 10, 20);
}
}
Output:

Handling Action Event Example:


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code="ButtonEvent3" width=300 height=100>
</applet>
*/

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 147


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public class ButtonEvent3 extends Applet implements ActionListener


{
Button a ;
String msg;
public void init( )
{
a=new Button("PVPSIT");
add(a);
a.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("PVPSIT")) msg="You pressed PVPSIT";
repaint ( );
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
}
}
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) { }

Table: Commonly used Listener Interfaces implemented by Adapter Classes

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 148


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Adapter Class Listener Interface


ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init( )
{
addMouseListener(new MyMouseAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo ad;
public MyMouseAdapter(AdapterDemo ad)
{
this.ad = ad;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{
ad.showStatus("Mouse clicked");
}
}

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>
*/

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 149


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public class InnerClassDemo extends Applet


{
String msg = "hello";
public void init()
{
addKeyListener(new MyKeyIn());
}
class MyKeyIn extends KeyAdapter
{
public void keyPressed(KeyEvent ke)
{showStatus("Key Pressed");
}
}
public void paint(Graphics g) { g.drawString(msg, 10, 20);
}
}

Anonymous Inner Classes:


An anonymous inner class is one that is not assigned a name.
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AInnerClassDemo" width=300 height=100>
</applet> */
public class AInnerClassDemo extends Applet
{
String msg = "hello";
public void init( )
{
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
showStatus("Key Pressed");
}
});
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, 10, 20);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 150


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

JAVA SWING INTRODUCTION:


➢ Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window
Toolkit [AWT].
➢ Java Swing offers much-improved functionality over AWT, new components, expanded
components features, and excellent event handling with drag-and-drop support.
What is JFC?
➢ JFC stands for Java Foundation Classes. JFC is the set of GUI components that simplify
desktop Applications.
➢ Many programmers think that JFC and Swing are one and the same thing, but that is not so.
➢ JFC contains Swing [A UI component package] and quite a number of other items:
✓ Cut and paste: Clipboard support.
✓ Accessibility features: Aimed at developing GUIs for users with disabilities.
✓ The Desktop Colors Features were first introduced in Java 1.1
✓ Java 2D: it has Improved colors, images, and text support.
Features Of Swing Class
✓ Pluggable look and feel.
✓ Uses MVC architecture.
✓ Lightweight Components
✓ Platform Independent
✓ Advanced features such as JTable, JTabbedPane, JScollPane, etc.
✓ Java is a platform-independent language and runs on any client machine, the GUI look
and feel, owned and delivered by a platform-specific O/S, simply does not affect an
application’s GUI constructed using Swing components.
✓ Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight
component development. For a component to qualify as lightweight, it must not depend
on any non-Java [O/s based) system classes. Swing components have their own view
supported by Java’s look and feel classes.
✓ Pluggable Look and Feel: This feature enable the user to switch the look and feel of
Swing components without restarting an application. The Swing library supports
components’ look and feels that remain the same across all platforms wherever the
program runs. The Swing library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application
✓ Highly customizable – Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
✓ Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane,
slider, colorpicker, and table controls.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 151


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Difference between AWT and Swing

No. Java AWT Java Swing

Java swing components are platform-


1) AWT components are platform-dependent.
independent.

2) AWT components are heavyweight. Swing components are lightweight.

AWT doesn't support pluggable look and


3) Swing supports pluggable look and feel.
feel.

Swing provides more powerful


AWT provides less components than
4) components such as tables, lists,
Swing.
scrollpanes, colorchooser, tabbedpane etc.

AWT doesn't follows MVC(Model View


Controller) where model represents data,
5) view represents presentation and controller Swing follows MVC.
acts as an interface between model and
view.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 152


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.
Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

sets the visibility of the component. It is by


public void setVisible(boolean b)
default false.

Java Swing Examples


There are two ways to create a frame:
✓ By creating the object of Frame class (association)
✓ By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.
➢ Let's see a simple swing example where we are creating one button and adding it on the JFrame
object inside the main() method.
FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[ ] args)
{
JFrame f=new JFrame( );//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 153


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Example of Swing by Association inside constructor


➢ We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.
Simple.java
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
public static void main(String[] args)
{
new Simple();
}
}
➢ The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets
the position of the button.

Components and Containers


➢ A Swing GUI consists of two key items: components and containers.
➢ A component is an independent visual control, such as a push button or slider.
➢ A container is a special type of component that is designed to hold other components.
➢ In order for a component to be displayed, it must be held within a container.
➢ Thus, all Swing GUIs will have at least one container. Because containers are components, a
container can also hold other containers.
Components
➢ In general, Swing components are derived from the JComponent class. All of Swing’s
components are represented by classes defined within the package javax.swing.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 154


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

JApplet class in Applet


➢ As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing.
The JApplet class extends the Applet class.
Example of EventHandling in JApplet:
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
public class EventJApplet extends JApplet implements ActionListener{
JButton b;
JTextField tf;
public void init(){
tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
}
➢ In the above example, we have created all the controls in init() method because it is invoked
only once.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 155


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

This class implements


protected class JFrame.AccessibleJFrame accessibility support for the
JFrame class.

Fields
Modifier and Type Field Description

The accessible context


protected AccessibleContext accessibleContext
property.

The exit application default


static int EXIT_ON_CLOSE
window close operation.

The JRootPane instance that


manages the contentPane and
protected JRootPane rootPane optional menuBar for this
frame, as well as the
glassPane.

If true then calls to add and


protected boolean rootPaneCheckingEnabled setLayout will be forwarded to
the contentPane.

Constructors
Constructor Description

It constructs a new frame that is initially


JFrame()
invisible.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 156


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

It creates a Frame in the specified


JFrame(GraphicsConfiguration gc) GraphicsConfiguration of a screen device and a
blank title.

It creates a new, initially invisible Frame with


JFrame(String title)
the specified title.

It creates a JFrame with the specified title and


JFrame(String title, GraphicsConfiguration gc) the specified GraphicsConfiguration of a screen
device.

Useful Methods
Modifier and Type Method Description

addImpl(Component comp, Object Adds the specified


protected void
constraints, int index) child Component.

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.

It sets the contentPane


void setContentPane(Containe contentPane)
property

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 sets the image to be


void setIconImage(Image image) displayed as the icon
for this window.

It sets the menubar for


void setJMenuBar(JMenuBar menubar)
this frame.

setLayeredPane(JLayeredPane It sets the layeredPane


void
layeredPane) property.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 157


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

It returns the rootPane


JRootPane getRootPane()
object for this frame.

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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 158


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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 Class Declaration


public class JPanel extends JComponent implements Accessible

Commonly used Constructors:


Constructor Description

It is used to create a new JPanel with a double


JPanel()
buffer and a flow layout.

It is used to create a new JPanel with


JPanel(boolean isDoubleBuffered) FlowLayout and the specified buffering
strategy.

It is used to create a new JPanel with the


JPanel(LayoutManager layout)
specified layout manager.

JPanel(ComponentOrientation orientation, Creates a new JPanel with the specified


boolean isDoubleBuffered) component orientation and buffering strategy.

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);

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 159


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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 class declaration


Let's see the declaration for javax.swing.JDialog class.
public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneCo
ntainer

Commonly used Constructors:


Constructor Description

It is used to create a modeless dialog without a


JDialog()
title and without a specified Frame owner.

JDialog(Frame owner) It is used to create a modeless dialog with

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 160


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

specified Frame as its owner and an empty


title.

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:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 161


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

JButton class declaration


Let's see the declaration for javax.swing.JButton class.
public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:


Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

It creates a button with the specified icon


JButton(Icon i)
object.
Commonly used Methods of AbstractButton class:
Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

It is used to set the specified Icon on the


void setIcon(Icon b)
button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

It is used to add the action listener to this


void addActionListener(ActionListener a)
object.
Example
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
} }

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 162


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Output:

JButton Example with ActionListener


import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:

Example of displaying image on the button:


import javax.swing.*;
public class ButtonExample{
ButtonExample(){
JFrame f=new JFrame("Button Example");
JButton b=new JButton(new ImageIcon("D:\\icon.png"));

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 163


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

This class implements


protected class JToggleButton.AccessibleJToggleButton accessibility support for
the JToggleButton class.

static class JToggleButton.ToggleButtonModel The ToggleButton model


Constructors
Constructor Description

It creates an initially unselected toggle button


JToggleButton()
without setting the text or image.

It creates a toggle button where properties are


JToggleButton(Action a)
taken from the Action supplied.

It creates an initially unselected toggle button


JToggleButton(Icon icon)
with the specified image but no text.

It creates a toggle button with the specified


JToggleButton(Icon icon, boolean selected)
image and selection state, but no text.

It creates an unselected toggle button with the


JToggleButton(String text)
specified text.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 164


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

It creates a toggle button with the specified


JToggleButton(String text, boolean selected)
text and selection state.

It creates a toggle button that has the specified


JToggleButton(String text, Icon icon)
text and image, and that is initially unselected.

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 gets the AccessibleContext


AccessibleContext getAccessibleContext() associated with this
JToggleButton.

It returns a string that


specifies the name of the l&f
String getUIClassID()
class that renders this
component.

It returns a string
protected String paramString() representation of this
JToggleButton.

It resets the UI property to a


void updateUI() value from the current look
and feel.

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);
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 165


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

private void setJToggleButton() {


button = new JToggleButton("ON");
add(button);
}
private void setAction() {
button.addItemListener(this);
}
public void itemStateChanged(ItemEvent eve) {
if (button.isSelected())
button.setText("OFF");
else
button.setText("ON");
}
}
Output

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

Creates an initially unselected check box


JJCheckBox()
button with no text, no icon.

Creates an initially unselected check box with


JChechBox(String s)
text.

Creates a check box with text and specifies


JCheckBox(String text, boolean selected)
whether or not it is initially selected.

Creates a check box where properties are


JCheckBox(Action a)
taken from the Action supplied.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 166


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Commonly used Methods:


Methods Description

It is used to get the AccessibleContext


AccessibleContext getAccessibleContext()
associated with this JCheckBox.

It returns a string representation of this


protected String paramString()
JCheckBox.

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:

JCheckBox Example with ItemListener


import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 167


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

final JLabel label = new JLabel();


label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
checkbox1.setBounds(150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
checkbox2.setBounds(150,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Output:

Java JCheckBox Example: Food Order


import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample extends JFrame implements ActionListener{
JLabel l;
JCheckBox cb1,cb2,cb3;
JButton b;
CheckBoxExample(){
l=new JLabel("Food Ordering System");
l.setBounds(50,50,300,20);
cb1=new JCheckBox("Pizza @ 100");

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 168


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 169


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

JRadioButton class declaration


Let's see the declaration for javax.swing.JRadioButton class.
public class JRadioButton extends JToggleButton implements Accessible
Commonly used Constructors:
Constructor Description

Creates an unselected radio button with no


JRadioButton()
text.

Creates an unselected radio button with


JRadioButton(String s)
specified text.

Creates a radio button with the specified text


JRadioButton(String s, boolean selected)
and selected status.

Commonly used Methods:


Methods Description

void setText(String s) It is used to set specified text on button.

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

It is used to set the specified Icon on the


void setIcon(Icon b)
button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

It is used to add the action listener to this


void addActionListener(ActionListener a)
object.

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);

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 170


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

ButtonGroup bg=new ButtonGroup();


bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}
Output:

JRadioButton Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 171


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public static void main(String args[]){


new RadioButtonExample();
}}

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.

JLabel class declaration


Let's see the declaration for javax.swing.JLabel class.
public class JLabel extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:
Constructor Description

Creates a JLabel instance with no image and


JLabel()
with an empty string for the title.

Creates a JLabel instance with the specified


JLabel(String s)
text.

Creates a JLabel instance with the specified


JLabel(Icon i)
image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified


horizontalAlignment) text, image, and horizontal alignment.

Commonly used Methods:


Methods Description

String getText() t returns the text string that a label displays.

It defines the single line of text this


void setText(String text)
component will display.

It sets the alignment of the label's contents


void setHorizontalAlignment(int alignment)
along the X axis.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 172


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

It returns the graphic image that the label


Icon getIcon()
displays.

It returns the alignment of the label's contents


int getHorizontalAlignment()
along the X axis.

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:

JLabel Example with ActionListener


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LabelExample extends Frame implements ActionListener{
JTextField tf; JLabel l; JButton b;
LabelExample(){
tf=new JTextField();
tf.setBounds(50,50, 150,20);
l=new JLabel();
l.setBounds(50,100, 250,20);
b=new JButton("Find IP");
b.setBounds(50,150,95,30);
b.addActionListener(this);
add(b);add(tf);add(l);

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 173


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

JTextField class declaration


Let's see the declaration for javax.swing.JTextField class.
public class JTextField extends JTextComponent implements SwingConstants
Commonly used Constructors:
Constructor Description

JTextField() Creates a new TextField

Creates a new TextField initialized with the


JTextField(String text)
specified text.

Creates a new TextField initialized with the


JTextField(String text, int columns)
specified text and columns.

Creates a new empty TextField with the


JTextField(int columns)
specified number of columns.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 174


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Commonly used Methods:


Methods Description

It is used to add the specified action listener to


void addActionListener(ActionListener l)
receive action events from this textfield.

It returns the currently set Action for this


Action getAction()
ActionEvent source, or null if no Action is set.

void setFont(Font f) It is used to set the current font.

It is used to remove the specified action


void removeActionListener(ActionListener l) listener so that it no longer receives action
events from this textfield.

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:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 175


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

JTextField Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}}
Output:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 176


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

Commonly Used Constructors

Constructor Description

Creates a text area that displays no text


JTextArea()
initially.

Creates a text area that displays specified text


JTextArea(String s)
initially.

Creates a text area with the specified number of


JTextArea(int row, int column)
rows and columns that displays no text initially.

Creates a text area with the specified number of


JTextArea(String s, int row, int column)
rows and columns that displays specified text.

Commonly Used Methods


Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of columns.

void setFont(Font f) It is used to set the specified font.

It is used to insert the specified text on the


void insert(String s, int position)
specified position.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 177


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

It is used to append the given text to the end of


void append(String s)
the document.

It retrieves the current number of rows in the


int getRows()
JTextArea.

It retrieves the current number of columns in


int getColumns()
the JTextArea.

It retrieves the current font used for text


Font getFont()
rendering in the JTextArea.

It sets the text content of the JTextArea to the


void setText(String text)
specified text.

String getText() It retrieves the text content of the JTextArea.

It sets whether the JTextArea is editable or


void setEditable(boolean editable)
not.

It sets whether lines in the JTextArea should


void setLineWrap(boolean wrap) be wrapped if they are too long to fit within
the width of the JTextArea.

It sets whether words in the JTextArea should


void setWrapStyleWord(boolean wrapWord) be wrapped at the nearest whitespace
character.

It appends the specified text to the end of the


void append(String str)
JTextArea's current text content.

It inserts the specified text at the specified


void insert(String str, int pos)
position within the JTextArea.

It replaces the text content within the specified


void replaceRange(String str, int start, int end)
range with the specified text.

It sets the foreground (text) color of the


void setForeground(Color fg)
JTextArea's text.

void setBackground(Color bg) It sets the background color of the JTextArea.


➢ These techniques provide a range of functions for adjusting JTextArea components'
appearance, behaviour, and content in Swing-based GUI applications.
➢ It allows developers to tailor JTextAreas to their own needs, be it changing the design, adding
text content, or performing text manipulation functions.

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.,

JFrame f= new JFrame();


JTextArea area=new JTextArea("Welcome to javatpoint");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}}
Output:

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.

JTextArea Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class TextAreaExample implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
l2=new JLabel();
l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 179


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

JList class declaration


Let's see the declaration for javax.swing.JList class.
public class JList extends JComponent implements Scrollable, Accessible

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 180


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Commonly used Constructors:


Constructor Description

Creates a JList with an empty, read-only,


JList()
model.

Creates a JList that displays the elements in


JList(ary[] listData)
the specified array.

Creates a JList that displays elements from the


JList(ListModel<ary> dataModel)
specified, non-null, model.

Commonly used Methods:


Methods Description

Void It is used to add a listener to the list, to be


addListSelectionListener(ListSelectionListener notified each time a change to the selection
listener) occurs.

It is used to return the smallest selected cell


int getSelectedIndex()
index.

It is used to return the data model that holds a


ListModel getModel()
list of items displayed by the JList component.

It is used to create a read-only ListModel from


void setListData(Object[] listData)
an array of objects.

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:

JList Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
final JLabel label = new JLabel();
label.setSize(500,100);
JButton b=new JButton("Show");
b.setBounds(200,150,80,30);
final DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("C");
l1.addElement("C++");
l1.addElement("Java");
l1.addElement("PHP");
final JList<String> list1 = new JList<>(l1);
list1.setBounds(100,100, 75,75);
DefaultListModel<String> l2 = new DefaultListModel<>();
l2.addElement("Turbo C++");
l2.addElement("Struts");
l2.addElement("Spring");
l2.addElement("YII");
final JList<String> list2 = new JList<>(l2);
list2.setBounds(100,200, 75,75);
f.add(list1); f.add(list2); f.add(b); f.add(label);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "";
if (list1.getSelectedIndex() != -1) {
data = "Programming language Selected: " + list1.getSelectedValue();
label.setText(data);
}
if(list2.getSelectedIndex() != -1){
data += ", FrameWork Selected: ";
for(Object frame :list2.getSelectedValues()){
data += frame + " ";

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 182


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

}
}
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.

JComboBox class declaration


Let's see the declaration for javax.swing.JComboBox class.
public class JComboBox extends JComponent implements ItemSelectable, ListDataListener,
ActionListener, Accessible
Commonly used Constructors:
Constructor Description

Creates a JComboBox with a default data


JComboBox()
model.

Creates a JComboBox that contains the


JComboBox(Object[] items)
elements in the specified array.

Creates a JComboBox that contains the


JComboBox(Vector<?> items)
elements in the specified Vector.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 183


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Commonly used Methods:


Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object anObject) It is used to delete an item to the item list.

void removeAllItems() It is used to remove all the items from the list.

It is used to determine whether the


void setEditable(boolean b)
JComboBox is editable.

void addActionListener(ActionListener a) It is used to add the ActionListener.

void addItemListener(ItemListener i) It is used to add the ItemListener.

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:

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 184


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

JComboBox Example with ActionListener


import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample();
}
}

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 185


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

Constructors
Constructor Purpose

JScrollPane() It creates a scroll pane. The


Component parameter, when
JScrollPane(Component) present, sets the scroll pane's
client. The two int
JScrollPane(int, int) parameters, when present, set
the vertical and horizontal
JScrollPane(Component, int, int) scroll bar policies
(respectively).

Useful Methods
Modifier Method Description

It sets the column header for the


void setColumnHeaderView(Component)
scroll pane.

It sets the row header for the


void setRowHeaderView(Component)
scroll pane.

void setCorner(String, Component) It sets or gets the specified


corner. The int parameter
specifies which corner and must
be one of the following constants
defined in ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
Component getCorner(String) LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Component) Set the scroll pane's client.

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

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 187


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

// java Program to create a simple JWindow


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solveit extends JFrame implements ActionListener {
// frame
static JFrame f;
// main class
public static void main(String[ ] args)
{
// create a new frame
f = new JFrame("frame");
// create a object
solveit 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(); }

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 188


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

// 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;

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 189


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

// 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); }

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 190


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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 :

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 191


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

23UCAP04 - PROGRAMMING IN JAVA LAB


1.Writea Java program that prompts the user for an integer and then prints out all the prime numbers
up to that Integer
2.Write a Java program to multiply two given matrices.
3.Write a Java program that displays the number of characters, lines and words in a text.
4.Generate random numbers between two given limits using Random class and print messages
according to the range of the value generated.
5.Write a program to do String Manipulation using Character Array and perform the Following string
operations:
a. String length
b. Finding a character at a particular position
c. Concatenating two strings
6.Write a program to perform the following string operations using String class:
a. String Concatenation
b. Search a substring
c. To extract substring from given string
7.Write a program to perform string operations using String Buffer class:
a. Length of a string
b. Reverse as tring
c. Delete a substring from the given string
8.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.
9.Write a threading program which uses the same method asynchronously to print the numbers 1 to 10
using Thread1 and to print 90 to 100 using Thread2.
10.Write a program to demonstrate the use of following exceptions.
a. ArithmeticException
b. NumberFormat Exception
c. ArrayIndexOutofBoundException
d. NegativeArraySizeException
11.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
12.Write a program to accept a text and change its size and font. Include bold italic options. Use
frames and controls.
13.Write a Java program that handles all mouse events and shows the event name at the centre of the
window when a mouse event is fired.(Use adapter classes).
14.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.
15.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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 192


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

1. Prime Number Generation

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;

public class PrimeNum


{
public static void main(String[ ] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = scanner.nextInt();
System.out.println("Prime numbers up to " + n + ":");
for (int i = 2; i <= n; i++)
{
if (isPrime(i))
{
System.out.println(i + " ");
}
}
}
public static boolean isPrime(int num)
{
if (num <= 1)
{
return false;
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 193


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

for (int i = 2; i * i <= num; i++)


{
if (num % i == 0)
{
return false;
}
}
return true;
}
}

OUTPUT:

D:\Naresh>set path=C:\jdk1.5.0\bin

D:\Naresh >javac PrimeNum.java

D:\Naresh >java PrimeNum


Enter an integer: 20
Prime numbers up to 20:
2 3 5 7 11 13 17 19

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 194


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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;

public class MatrixMultiplication


{
public static void main(String[ ] args)
{
int i,j,k;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows and columns in the first matrix: ");
int r1 = scanner.nextInt( );
int c1 = scanner.nextInt( );
System.out.print("Enter the number of rows and columns in the second matrix: ");
int r2 = scanner.nextInt( );
int c2 = scanner.nextInt( );
int a[ ][ ] = new int[r1][c1];
int b[ ][ ]= new int[r2][c2];
int c[ ][ ] = new int[r1][c1];
if(c1 == r2)
{
System.out.println("\n Enter first matrix:\n");
for(i=0 ; i<r1 ; ++i)
for(j=0 ; j<c1 ; ++j)
a[i][j] = scanner.nextInt( );
System.out.println("\n Enter second matrix:\n");
for(i=0 ; i<r2 ; ++i)
for(j=0 ; j<c2 ; ++j)
b[i][j]= scanner.nextInt( );

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 195


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

System.out.println("\n The Multiplication result matrix is:\n");


for(i=0 ; i<r1 ; ++i)
{
for(j=0 ; j<c2 ; ++j)
{
c[i][j]=0;
for(k=0 ; k<c1 ; ++k)
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
System.out.print("\t"+c[i][j]);
}
System.out.println("\n");
}
}
else
System.out.println("\nSorry!!!! Matrix multiplication can't be done");
}
}

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 196


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

3. Displays the number of characters, lines and words in a text

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;
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 197


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public static int countWords(String text)


{
String[ ] words = text.split("\\s+");
return words.length;
}
}

OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin

D:\Naresh >javac TextStat.java

D:\Naresh >java TextStat


Enter a text:
All is Well
The Lion is always Lion
^Z

Text statistics:
Characters: 37
Lines: 2
Words: 8

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 198


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

4. Random Numbers Generation

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;

public class RandomNumGen


{
public static void main(String[ ] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the lower limit: ");
int LL = scanner.nextInt( );
System.out.print("Enter the upper limit: ");
int UL = scanner.nextInt( );
Random random = new Random();
int RN = random.nextInt(UL - LL + 1) + LL;
System.out.println("Random number generated: " + RN);
if (RN < (LL + (UL - LL) / 3))
{
System.out.println("Random number is in the lower third of the range.");
}
else if (RN < (LL + 2 * (UL - LL) / 3))
{
System.out.println("Random number is in the middle third of the range.");
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 199


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

else
{
System.out.println("Random number is in the upper third of the range.");
}
}
}

OUTPUT:

D:\Naresh >set path=C:\jdk1.5.0\bin

D:\Naresh >javac RandomNumGen.java

D:\Naresh >java RandomNumGen


Enter the lower limit: 1
Enter the upper limit: 10
Random number generated: 7
Random number is in the upper third of the range.

D:\Naresh >java RandomNumGen


Enter the lower limit: 5
Enter the upper limit: 10
Random number generated: 5
Random number is in the lower third of the range.

D:\Naresh >java RandomNumGen


Enter the lower limit: 2
Enter the upper limit: 8
Random number generated: 5
Random number is in the middle third of the range.

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 200


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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;

public class StringManipulation


{
public static void main(String[ ] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine( );
System.out.print("Enter the second string: ");
String str2 = scanner.nextLine( );
char[ ] charArray1 = str1.toCharArray( );
char[ ] charArray2 = str2.toCharArray( );
System.out.println("Length of string 1: " + charArray1.length);
System.out.println("Length of string 2: " + charArray2.length);
System.out.print("Enter the position to find the character in string 1 (0-" +
(charArray1.length - 1) + "): ");
int position = scanner.nextInt();
scanner.nextLine( );
if (position >= 0 && position < charArray1.length)
{
System.out.println("Character at position " + position + " in string 1: " +
charArray1[position]);
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 201


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

D:\Naresh >javac StringManipulation.java

D:\Naresh >java StringManipulation


Enter the first string: Naresh
Enter the second string: kumar
Length of string 1: 6
Length of string 2: 5
Enter the position to find the character in string 1 (0-5): 3
Character at position 3 in string 1: e
Concatenated string: Nareshkumar

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 202


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

6. String Operations using String class.

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;

public class StringOperations


{
public static void main(String[ ] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine( );
System.out.print("Enter the second string: ");
String str2 = scanner.nextLine( );
String conString = str1 + " " + str2;
System.out.println("Concatenated string: " + conString);
System.out.print("Enter a substring to search in string 1: ");
String substring = scanner.nextLine( );
if (str1.contains(substring))
{
System.out.println("Substring found in string 1");
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 203


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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

D:\Naresh >javac StringOperations.java

D:\Naresh >java StringOperations


Enter the first string: Vinod
Enter the second string: kumar
Concatenated string: Vinod kumar
Enter a substring to search in string 1: no
Substring found in string 1
Enter the starting index of the substring to extract from string 1: 0
Enter the ending index of the substring to extract from string 1: 3
Extracted substring: Vin

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 204


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

7. String Operations using String Buffer class

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");
} }
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 205


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin

D:\Naresh >javac StringBufferOperations.java

D:\Naresh >java StringBufferOperations


D:\Naresh >java StringBufferOperations
Enter a string: Welcome
Length of the string: 7
Reversed string: emocleW
Enter a substring to delete from the string: oc
String after deleting the substring: emleW

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 206


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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;
}
}

class GeneratorThread extends Thread


{
private Shared shared;
private Random random;
private int count;
public GeneratorThread(Shared shared)
{
this.shared = shared;
this.random = new Random( );
this.count = 0;
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 208


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public void run( )


{
while (count < 5)
{
int number = random.nextInt(10);
shared.setNumber(number);
System.out.println("Generated number: " + number);
count++;
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
Thread.currentThread( ).interrupt( );
}
}
shared.setStop(true);
}
}
class SquareThread extends Thread
{
private Shared shared;
public SquareThread(Shared shared)
{
this.shared = shared;
}
public void run( )
{
while (true)
{
int number = shared.getNumber( );
if (shared.isStop( ))
{
break;
}
if (shared.isEven( ))
{
int square = number * number;
System.out.println("Square of " + number + ": " + square);
}
}
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 209


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

class CubeThread extends Thread


{
private Shared shared;
public CubeThread(Shared shared)
{
this.shared = shared;
}

public void run( )


{
while (true)
{
int number = shared.getNumber( );
if (shared.isStop( ))
{
break;
}
if (!shared.isEven( ))
{
int cube = number * number * number;
System.out.println("Cube of " + number + ": " + cube);
}
}
}
}

public class MultiThreadApp1


{
public static void main(String[ ] args)
{
Shared shared = new Shared( );
GeneratorThread gThread = new GeneratorThread(shared);
SquareThread sThread = new SquareThread(shared);
CubeThread cThread = new CubeThread(shared);
gThread.start( );
sThread.start( );
cThread.start( );
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 210


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin

D:\Naresh >javac MultiThreadApp1.java

D:\Naresh >java MultiThreadApp1


Generated number: 9
Generated number: 5
Cube of 5: 125
Generated number: 2
Generated number: 6
Generated number: 6
Square of 6: 36

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 211


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

9. Inter Thread Communication.

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.*;

// Thread to print numbers 1 to 10


class Thread1 extends Thread
{
public void run( )
{
for (int i = 1; i <= 10; i++)
{
System.out.println("Thread1: " + i);
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
Thread.currentThread( ).interrupt( );
}
}
}
}
// Thread to print numbers 90 to 100
class Thread2 extends Thread
{
public void run( )
{
for (int i = 90; i <= 100; i++)
{

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 212


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

System.out.println("Thread2: " + i);


try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
Thread.currentThread( ).interrupt( );
}
}
}
}

public class MultiThreadApp2


{
public static void main(String[ ] args)
{
Thread1 t1 = new Thread1( );
Thread2 t2 = new Thread2( );
t1.start();
t2.start();
}
}

OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin

D:\Naresh >javac MultiThreadApp2.java

D:\Naresh >java MultiThreadApp2


Thread1: 1
Thread2: 90
Thread2: 91
Thread1: 2
Thread2: 92
Thread1: 3
Thread1: 4
Thread2: 93
Thread2: 94
Thread1: 5
Thread2: 95
Thread1: 6
Thread2: 96
Thread1: 7

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 213


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 214


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

10. Exception Handling

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

D:\Naresh >javac ExceptionDemo.java

D:\Naresh >java ExceptionDemo


ArithmeticException caught: / by zero
NumberFormatException caught: For input string: "bca"
ArrayIndexOutOfBoundsException caught: 10
NegativeArraySizeException caught: null

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 216


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

11. File Handling

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;

public class FileInfo


{
public static void main(String[ ] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a file name:");
String fileName = scanner.next( );
File file = new File(fileName);
System.out.println("File Name: " + file.getName( ));
System.out.println("File Exists: " + file.exists( ));
System.out.println("File is Readable: " + file.canRead( ));
System.out.println("File is Writable: " + file.canWrite( ));
if (file.isFile( ))
{
System.out.println("File Type: Regular File");
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 217


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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:

D:\Naresh >set path=C:\jdk1.5.0\bin

D:\Naresh >javac FileInfo.java

D:\Naresh >java FileInfo


Enter a file name:
FileInfo.java
File Name: FileInfo.java
File Exists: true
File is Readable: true
File is Writable: true
File Type: Regular File
File Length: 890 bytes

D:\Naresh >java FileInfo


Enter a file name:
rose.txt
File Name: rose.txt
File Exists: false
File is Readable: false
File is Writable: false
File Type: Unknown
File Length: 0 bytes

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 218


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

12. Frames and controls

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;

public class TextEditor1 extends JFrame


{
private JTextArea textArea;
private JSpinner fontSizeSpinner;
private JComboBox fontComboBox;
private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;
public TextEditor1( )
{
// Create text area
textArea = new JTextArea(20, 40);
textArea.setFont(new Font("Arial", Font.PLAIN, 12));
// Create font size spinner
fontSizeSpinner = new JSpinner(new SpinnerNumberModel(12, 8, 48, 1));

fontSizeSpinner.addChangeListener(new ChangeListener( )

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 219


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

{
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)
{

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 220


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

int style = textArea.getFont().getStyle( );


if (italicCheckBox.isSelected( ))
{
style |= Font.ITALIC;
}
else
{
style &= ~Font.ITALIC;
}
textArea.setFont(new Font(textArea.getFont( ).getName( ), style,
textArea.getFont().getSize( )));
}
});
// Create panel for controls
JPanel controlPanel = new JPanel( );
controlPanel.setLayout(new FlowLayout( ));
controlPanel.add(new JLabel("Font Size:"));
controlPanel.add(fontSizeSpinner);
controlPanel.add(new JLabel("Font:"));
controlPanel.add(fontComboBox);
controlPanel.add(boldCheckBox);
controlPanel.add(italicCheckBox);
// Create frame
add(new JScrollPane(textArea), BorderLayout.CENTER);
add(controlPanel, BorderLayout.NORTH);
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[ ] args)
{
new TextEditor1( );
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 221


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

OUTPUT:

D:\Naresh >javac TextEditor1.java

D:\Naresh >java TextEditor1

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 222


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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 class MouseEventHandler extends JPanel


{
private JLabel label;

public MouseEventHandler()
{
label = new JLabel("", JLabel.CENTER);
add(label);
addMouseListener(new MouseAdapter( )
{
public void mousePressed(MouseEvent e)
{
showEvent("Mouse Pressed");
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 223


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

public void mouseReleased(MouseEvent e)


{
showEvent("Mouse Released");
}
public void mouseEntered(MouseEvent e)
{
showEvent("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
showEvent("Mouse Exited");
}
});

addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
showEvent("Mouse Dragged");
}
public void mouseMoved(MouseEvent e)
{
showEvent("Mouse Moved");
}
});
}

private void showEvent(String event)


{
label.setText(event);
label.repaint( );
}

public static void main(String[ ] args)


{
JFrame frame = new JFrame("Mouse Event Handler");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MouseEventHandler( ));
frame.setSize(400, 300);
frame.setVisible(true);
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 224


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

OUTPUT:

D:\Naresh >set path=C:\jdk1.5.0\bin

D:\Naresh >javac MouseEventHandler.java

D:\Naresh >java MouseEventHandler

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 225


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

14. Simple calculator using Java Swing

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.*;

public class Calculator extends JFrame


{
private JTextField resultField;
private double number1, number2, result;
private char operation;
public Calculator( )
{
resultField = new JTextField(20);
resultField.setEditable(false);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
String[ ] buttons = {"7", "8", "9", "/", "4", "5", "6", "*","1", "2", "3", "-","0", ".", "=", "+"};
for (String button : buttons)
{
JButton btn = new JButton(button);
btn.addActionListener(new ButtonListener( ));
buttonPanel.add(btn);
}
add(resultField, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 226


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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");
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 227


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

else if (command.equals("+") || command.equals("-") || command.equals("*") ||


command.equals("/"))
{
number1 = Double.parseDouble(resultField.getText());
operation = command.charAt(0);
resultField.setText("");
} else {
resultField.setText(resultField.getText() + command);
}
}
}
public static void main(String[ ] args)
{
new Calculator();
}
}
OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin
D:\Naresh >javac Calculator.java
D:\Naresh >java Calculator

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 228


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

15. Simulation of Traffic light using Java Swing.

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 class TrafficLight extends JFrame


{
private JRadioButton redButton, yellowButton, greenButton;
private JLabel messageLabel;

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();

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 229


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

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();
}
}

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 230


23UCA04- PROGRAMMING IN JAVA M.NARESHKUMAR M.C.A.,M.Phil.,B.Ed.,

OUTPUT:
D:\Naresh >set path=C:\jdk1.5.0\bin

D:\Naresh >javac TrafficLight.java

D:\Naresh >java TrafficLight

RESULT :
Thus, the above program has been created successfully and the outputs are verified.

ARIGNAR ANNA COLLEGE(ARTS & SCIENCE) - KRISHNAGIRI Page 231

You might also like