Oop Java
Oop Java
UNIT – I:
Introduction: OOP concepts, history of Java, Java buzzwords, data types, variables, scope and life
time of variables, arrays, operators, expressions, control statements, type conversion and casting,
simple java program.
Classes and Objects: concepts of classes, objects, constructors, methods, this keyword, garbage
collection, overloading methods and constructors, parameter passing, recursion.
String handling: String, String Buffer, String Tokenize.
UNIT – II:
Inheritance: base class object, subclass, member access rules, super uses,using final with
inheritance, method overriding, abstract classes
Interfaces: defining an interface, implementing interface, differences betweenclasses and
interfaces and extending interfaces.
Packages: Defining, creating and accessing a package, importing packages,access control,
exploring package - java.io
UNIT – III:
Exception handling: concepts of exception handling, benefits of exception handling, exception
hierarchy, checked and unchecked exceptions, usage of- try, catch, throw, throws and finally, built
in exceptions, creating own exception sub classes.
Multithreading: differences between multi-threading and multitasking, thread
life cycle, creating threads, synchronizing threads, daemon threads, thread groups.
UNIT – IV:
Applets: concepts of applets, differences between applets and applications, life cycle of applet,
types of applets, creating applets, passing parameters to applets.
Event Handling: events, event sources, event classes, event listeners, delegation event model,
handling mouse and key board events, adapter classes. The AWT class hierarchy, user interface
components-labels, buttons, canvas, scrollbars, text components, checkbox, checkbox groups,
choices, lists
2
UNIT – V:
Layout manager: layout manager types-border, grid, flow, card and grid bag. Swing:
Introduction, limitations of AWT, components, containers,
Exploring swing- JApplet, JFrame and JComponent, Icons and Labels, Text fields, buttons – The
JButton class, Checkboxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes, Trees and
Tables.
TEXT BOOKS:
1. Java The complete reference, 8th editon, Herbert Schildt, TMH.
2. Understanding OOP with Java, up dated edition, T.Budd, Pears oneducation.
REFERENCE BOOKS :
1. An Introduction to programming and OO design using Java, J. Ninoand F.A. Hosch,
John Wiley & sons.
2. An Introduction to OOP, second edition, T. Budd, pearson
education.
3. Introduction to Java programming 6th edition, Y. Daniel Liang,
pearson education.
3
James Gosling is a famous Canadian software developer who has been with Sun
Microsystems since 1984 and is considered as father of Java programming language Gosling
did the original design of Java and implemented its original compiler and virtual machine
4
UNIT-I
INTRODUCTION
History of Java:
In 1990, Sun Micro Systems Inc (US) was conceived a project to develop software for
consumer electronic devices that could be controlled by a remote This project was called
Stealth Project but later its name was changed to Green Project
In January 1991, Project Manager James Gosling and his team members Patrick Naughton,
Mike Sheridan, Chris Wrath, and Ed Frank met to discuss about this project
Gosling thought C and C++ would be used to develop the project But the problem he faced
with them is that they were system dependent languages The trouble with C and C++ (and
most other languages) is that they are designed to be compiled for a specific target and
could not be used on various processors, which the electronic devices might use
James Gosling with his team started developing a new language, which was completely
system independent This language was initially called OAK Since this name was
registered by some other company, later it was changed to Java
James Gosling and his team members were consuming a lot of coffee while developing
this language Good quality of coffee was supplied from a place called “Java Island‟ Hence
they fixed the name of the language as Java The symbol for Java language is cup and
saucer
Sun formally announced Java at Sun World conference in 1995 On January 23 rd 1996,
JDK10 version was released
Setting up Java Environment: After installing the JDK, we need to set at least one
environment variable in order to able to compile and run Java programs A PATH environment
variable enables the operating system to find the JDK executables when our working directory
is not the JDK's binary directory
Setting environment variables from a command prompt: If we set the variables from a
command prompt, they will only hold for that session To set the PATH from a command
prompt:
set PATH=C:\Program Files\Java\jdk150_05\bin;%PATH%
o Right-click on My Computer
o Choose Properties
o Select the Advanced tab
o Click the Environment Variables
button at the bottom
o In system variables tab, select
path (system variable) and click
on edit button
o A window with variable name-
path and its value will be
displayed
o Don‟t disturb the default path
value that is appearing and just
append (add) to that path at the
end:
;C:\ProgramFiles\Java\
jdk150_05\bin;
o Finally press OK button
6
Programming Structure
Comments: Comments are description about the aim and features of the program Comments
increase readability of a program Three types of comments are there in Java:
Single line comments: These comments start with //
eg: // this is comment line
Multi line comments: These comments start with /* and end with */
eg: /* this is comment line*/
Java documentation comments: These comments start with /** and end with */
These comments are useful to create a HTML file called API (application programming
Interface) document This file contains description of all the features of software
method as static JVM calls main () method using its Classnamemain () at the time of
running the program.JVM is a program written by Java Soft people (Java development
team) and main () is the method written by us Since, main () method should be available to
the JVM, it should be declared as public If we don‟t declare main () method as public, then
it doesn‟t make itself available to JVM and JVM cannot execute it
JVM always looks for main () method with String type array as parameter otherwise JVM
cannot recognize the main () method, so we must provide String type array as parameter to
main () method
A class code starts with a {and ends with a} A class or an object contains variables and
methods (functions) We can create any number of variables and methods inside the class
This is our first program, so we had written only one method called main ()
Our aim of writing this program is just to display a string “Hello world” In Java, print ()
method is used to display something on the monitor
A method should be called by using objectnamemethodname () So, to call print () method,
create an object to PrintStream class then call objectnameprint () method
An alternative is given to create an object to PrintStream Class ie Systemout Here, System
is the class name and out is a static variable in System class out is called a field in System
class When we call this field a PrintStream class object will be created internally So, we
can
call print() method as: Systemoutprint (“Hello world”);
println () is also a method belonging to PrintStream class It throws the cursor to the next
line after displaying the result
In the above Sample program System and String are the classes present in javalang
package
Escape Sequence: Java supports all escape sequence which is supported by C/ C++ A
character preceded by a backslash (\) is an escape sequence and has special meaning to the
compiler When an escape sequence is encountered in a print statement, the compiler interprets
it accordingly
Using the Save in combo box, specify the folder (directory) where you'll save your file
In the File name text field, type "Samplejava", including the quotation marks Then
the dialog box should look like this:
The prompt shows current directory To compile Samplejava source file, change current
directory to the directory where Samplejava file is located For example, if source directory
is JQR on the D drive, type the following commands at the prompt and press Enter:
The Java Virtual Machine: Java Virtual Machine (JVM) is the heart of entire Java program
execution process First of all, the java program is converted into a class file consisting of byte
code instructions by the java compiler at the time of compilation Remember, this java
compiler is outside the JVM This class file is given to the JVM Following figure shows the
architecture of Java Virtual Machine
.If the byte instructions are proper, then it allocates necessary memory to execute the program
This memory is divided into 5 parts, called run time data areas, which contain the data and
results while running the program These areas are as follows:
o Method area: Method area is the memory block, which stores the class code, code of
the variables and code of the methods in the Java program (Method means functions
written in a class)
o Heap: This is the area where objects are created Whenever JVM loads a class, method
and heap areas are immediately created in it
o Java Stacks: Method code is stored on Method area But while running a method, it
needs some more memory to store the data and results This memory is allotted on Java
Stacks So, Java Stacks are memory area where Java methods are executed While
executing methods, a separate frame will be created in the Java Stack, where the
method is executed JVM uses a separate thread (or process) to execute each method
o PC (Program Counter) registers: These are the registers (memory areas), which
contain memory address of the instructions of the methods If there are 3 methods, 3 PC
registers will be used to track the instruction of the methods
o Native Method Stacks: Java methods are executed on Java Stacks Similarly, native
methods (for example C/C++ functions) are executed on Native method stacks To
execute the native methods, generally native method libraries (for example C/C++
header
files) are required These header files are located and connected to JVM by a program,
called Native method interface
Execution Engine contains interpreter and JIT compiler which translates the byte code
instructions into machine language which are executed by the microprocessor Hot spot
(loops/iterations) is the area in class file ie executed by JIT compiler JVM will identify the
Hot spots in the class files and it will give it to JIT compiler where the normal instructions and
statements of Java program are executed by the Java interpreter
Data Types: The classification of data item is called data type Java defines eight simple
types of data byte, short, int, long, char, float, double and boolean These can be put in four
groups:
Integer Data Types:These data types store integer numbers
.
Bitwise operators: These operators act on individual bits (0 and 1) of the operands They
act only on integer data types, ie byte, short, long and int
Operator Meaning Explanation
& Bitwise AND Multiplies the individual bits of operands
| Bitwise OR Adds the individual bits of operands
^ Bitwise XOR Performs Exclusive OR operation
<< Left shift Shifts the bits of the number towards left a specified
number of positions
>> Right shift Shifts the bits of the number towards right a
specified number of positions and also preserves the
sign bit
>>> Zero fill right shift Shifts the bits of the number towards right a
specified number of positions and it stores 0 (Zero)
in the sign bit
~ Bitwise complement Gives the complement form of a given number by
changing 0‟s as 1‟s and vice versa
Ternary Operator or Conditional Operator (? :): This operator is called ternary because it
acts on 3 variables The syntax for this operator is:
Variable = Expression1? Expression2: Expression3;
First Expression1 is evaluated If it is true, then Expression2 value is stored into variable
otherwise Expression3 value is stored into the variable
eg: max = (a>b) ? a: b;
Control Statements
Control statements are the statements which alter the flow of execution and provide better
control to the programmer on the flow of execution In Java control statements are categorized
into selection control statements, iteration control statements and jump control statements
Java’s Selection Statements: Java supports two selection statements: if and switch These
statements allow us to control the flow of program execution based on condition
if Statement: if statement performs a task depending on whether a condition is true or
false
Syntax: if (condition)
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement enclosed in
curly braces (that is, a block) The condition is any expression that returns a boolean
value The else clause is optional
Switch Statement: When there are several options and we have to choose only one
option from the available ones, we can use switch statement
Syntax:switch (expression)
{case value1: //statement sequence
break;
case value2: //statement sequence
16
break;
……………
case valueN: //statement sequence
break;
default: //default statement sequence
}
Here, depending on the value of the expression, a particular corresponding case will be
executed
Program 2: Write a program for using the switch statement to execute a particular
task depending on color value
//To display a color name depending on color
value class ColorDemo
{public static void main(String args[])
{char color = „r‟;
switch (color)
{ case „r‟: Systemoutprintln (“red”); break;
case „g‟: Systemoutprintln (“green”); break;
case „b‟: Systemoutprintln (“blue”); break;
case „y‟: Systemoutprintln (“yellow”); break;
case „w‟: Systemoutprintln (“white”); break;
default: Systemoutprintln (“No Color Selected”);
}
}
}
Output:
Java’s Iteration Statements: Java‟s iteration statements are for, while and do-while
These statements are used to repeat same set of instructions specified number of times
called loops A loop repeatedly executes the same set of instructions until a termination
condition is met
while Loop: while loop repeats a group of statements as long as condition is true Once
the condition is false, the loop is terminated In while loop, the condition is tested first;
if it is true, then only the statements are executed while loop is called as entry control
loop
Syntax:while (condition)
{
statements;
}
17
. for Loop: The for loop is also same as do…while or while loop, but it is more compact
syntactically The for loop executes a group of statements as long as a condition is true
Syntax: for (expression1; expression2; expression3)
{ statements;
}
Here, expression1 is used to initialize the variables, expression2 is used for condition
checking and expression3 is used for increment or decrement variable value
Java’s Jump Statements: Java supports three jump statements: break, continue and return
These statements transfer control to another part of the program
o break:
break can be used inside a loop to come out of it
break can be used inside the switch block to come out of the switch block
break can be used in nested blocks to go to the end of a block Nested blocks
represent a block written within another block
Syntax: break; (or) break label;//here label represents the name of the block
continue: This statement is useful to continue the next repetition of a loop/ iteration
When continue is executed, subsequent statements inside the loop are not executed
Syntax:continue;
return statement:
return statement is useful to terminate a method and come back to the calling
method
return statement in main method terminates the application
return statement can be used to return some value from a method to a calling
method
Syntax:return;
(or)
return value; // value may be of any type
return;
Systemoutprintln (“This won‟t execute”);
}
}
Output:
Note: goto statement is not available in java, because it leads to confusion and forms infinite
loops.
A stream represents flow of data from one place to other place Streams are of two types in
java Input streams which are used to accept or receive data Output streams are used to display
or write data Streams are represented as classes in javaio package
Systemin: This represents InputStream object, which by default represents standard input
device that is keyboard
Systemout: This represents PrintStream object, which by default represents standard
output device that is monitor
Systemerr: This field also represents PrintStream object, which by default represents
monitor Systemout is used to display normal messages and results whereas Systemerr is
used to display error messages
BufferedReader
InputStreamReader
Keyboard
Systemin
Figure: Reading data from keyboard
parseInt () is a static method in Integer class, so it can be called using class name as
IntegerparseInt ()
We are not using casting to convert String type into int type The reason is String is a class
and int is a fundamental data type Converting a class type into a fundamental data type is
not possible by using casting It is possible by using the method IntegerparseInt()
. .
throws IOException at the side of the method where read ()/ readLine () is used
In the above program after accepting gender of the student, brskip (2) is used The
reason is that we used read () method to accept the gender value and then readLine () is used
to accept the name When we type M for gender and press enter, then it releases a \n code So at
gender column, we are giving two characters M and \n But, read () method takes only the first
character and rejects the next character, ie \n, which is trapped by the next readLine () method
and name will accept \n For this purpose, we can use skip () method of BufferedReader, which
helps in skipping a specified number of characters Suppose we take \n as two characters; now
to skip them, we can write brskip (2);
24
. .
Arrays and Strings
Arrays: An array represents a group of elements of same data type Arrays are generally
categorized into two types:
Single Dimensional arrays (or 1 Dimensional arrays)
Multi-Dimensional arrays (or 2 Dimensional arrays, 3 Dimensional arrays, …)
Single Dimensional Arrays: A one dimensional array or single dimensional array represents
a row or a column of elements For example, the marks obtained by a student in 5 different
subjects can be represented by a 1D array
We can declare a one dimensional array and directly store elements at the time of its
declaration, as: int marks[] = {50, 60, 55, 67, 70};
We can create a 1D array by declaring the array first and then allocate memory for it by
using new operator, as: int marks[]; //declare marks array
marks = new int[5]; //allot memory for storing 5 elements
These two statements also can be written as: int marks [] = new int [5];
Program 1: Write a program to accept elements into an array and display the same
program to accept elements into an array and display the
same import javaio*;
class ArrayDemo1
{public static void main (String args[]) throws IOException
{//Create a BufferedReader class object (br)
BufferedReader br = new BufferedReader (new InputStreamReader
(Systemin));
Systemoutprintln (“How many elements: “ );
int n = IntegerparseInt (brreadLine ());
//create a 1D array with size n
int a[] = new int[n];
Systemoutprint ("Enter elements into array : ");
for (int i = 0; i<n;i++)
a [i] = IntegerparseInt ( brreadLine ());
Systemoutprint (“The entered elements in the array are:
“); for (int i =0; i < n; i++)
Systemoutprint (a[i] + “\t”);
}
}
Output:
25
Program 2: Write a program to take a 2D array and display its elements in the form of a
matrix
//Displaying a 2D array as a matrix
class Matrix
{public static void main(String args[])
{//take a 2D array
int x[ ][ ] = {{1, 2, 3}, {4, 5, 6}
}; // display the array elements
for (int i = 0 ; i < 2 ; i++)
{Systemoutprintln (); for (int j
= 0 ; j < 3 ; j++)
Systemoutprint(x[i][j] + “\t”);
}
}
}
Output:
Three Dimensional arrays (3D arrays): We can consider a three dimensional array as a
combination of several two dimensional arrays To represent a three dimensional array, we
should use three pairs of square braces [ ] [ ] after the array name
o We can declare a three dimensional array and directly store elements at the time of its
declaration, as:
int arr[ ] [ ] [ ] = {{{50, 51, 52},{60, 61, 62}}, {{70, 71, 72}, {80, 81, 82}}};
26
. .
We can create a three dimensional array by declaring the array first and then we can allot
memory for it by using new operator as:
int arr[ ] [ ] = new int[2][2][3]; //allot memory for storing 15 elements
arraynamelength: If we want to know the size of any array, we can use the property „length‟
of an array In case of 2D, 3D length property gives the number of rows of the array
Strings: A String represents group of characters Strings are represented as String objects in
java
Creating Strings:
We can declare a String variable and directly store a String literal using assignment
operator String str = "Hello";
We can create String object using new operator with some data
. .
. .
}
Output:
We can divide objects broadly as mutable and immutable objects Mutable objects are those
objects whose contents can be modified Immutable objects are those objects, once created can
not be modified String objects are immutable The methods that directly manipulate data of the
object are not available in String class
StringBuffer: StringBuffer objects are mutable, so they can be modified The methods that
directly manipulate data of the object are available in StringBuffer class
Creating StringBuffer:
We can create a StringBuffer object by using new operator and pass the string to the object,
as: StringBuffer sb = new StringBuffer ("Kiran");
We can create a StringBuffer object by first allotting memory to the StringBuffer object
using new operator and later storing the String into it as:
StringBuffer sb = new StringBuffer (30);
In general a StringBuffer object will be created with a default capacity of 16 characters Here,
StringBuffer object is created as an empty object with a capacity for storing 30 characters
Even if we declare the capacity as 30, it is possible to store more than 30 characters into
StringBuffer To store characters, we can use append () method as:
Sbappend (“Kiran”);
.
Introduction to OOPs
Languages like Pascal, C, FORTRAN, and COBOL are called procedure oriented
programming languages Since in these languages, a programmer uses procedures or functions
to perform a task When the programmer wants to write a program, he will first divide the task
into separate sub tasks, each of which is expressed as functions/ procedures This approach is
called procedure oriented approach
The languages like C++ and Java use classes and object in their programs and are
called Object Oriented Programming languages The main task is divided into several modules
and these are represented as classes Each class can perform some tasks for which several
methods are written in a class This approach is called Object Oriented approach
Features of OOP:
Class: In object-oriented programming, a class is a programming language construct that
is used as a blueprint to create objects This blueprint includes attributes and methods that
the created objects all share Usually, a class represents a person, place, or thing - it is an
abstraction of a concept within a computer program Fundamentally, it encapsulates the
state
31
. .
and behavior of that which it conceptually represents It encapsulates state through data
placeholders called member variables; it encapsulates behavior through reusable code
called methods
General form of a class class_name
class: {
Properties (variables);
Actions (methods);
}
eg: class Student
{//properties -- variables int
rollNo;
String name;
//methods --
actions void
display ()
{
Systemoutprintln ("Student Roll Number is: " + rollNo);
Systemoutprintln ("Student Name is: " + name);
}
}
Note: Variables inside a class are called as instance variables
Variables inside a method are called as method variables
Object: An Object is a real time entity An object is an instance of a class Instance means
physically happening An object will have some properties and it can perform some actions
Object contains variables and methods The objects which exhibit similar properties and
actions are grouped under one class “To give a real world analogy, a house is constructed
according to a specification Here, the specification is a blueprint that represents a class,
and the constructed house represents the object”
o To access the properties and methods of a class, we must declare a variable of that class
type This variable does not define an object Instead, it is simply a variable that can
refer to an object
o We must acquire an actual, physical copy of the object and assign it to that variable We
can do this using new operator The new operator dynamically allocates memory for an
object and returns a reference to it This reference is, more or less, the address in
memory of the object allocated by new This reference is then stored in the variable
Thus, in Java, all class objects must be dynamically allocated
General form of an Object:
Class_name variable_name; // declare reference to object
variable_name = new Class_name ( ); // allocate an object
eg: Student s; // s is reference variable
s = new Student (); // allocate an object to reference variable s
32
The above two steps can be combined and rewritten in a single statement as:
Student s = new Student ();
Now we can access the properties and methods of a class by using object with
dot operator as:
srollNo, sname, sdisplay ()
. .
Encapsulation: Wrapping up of data (variables) and methods into single unit is called
Encapsulation Class is an example for encapsulation Encapsulation can be described as a
protective barrier that prevents the code and data being randomly accessed by other code
defined outside the class Encapsulation is the technique of making the fields in a class
private and providing access to the fields via methods If a field is declared private, it
cannot be accessed by anyone outside the class
eg: class Student
{
private int rollNo;
private String name;
//methods -- actions
void display ()
{
Systemoutprintln ("Student Roll Number is: " + rollNo);
Systemoutprintln ("Student Name is: " + name);
}
}
Abstraction: Providing the essential features without its inner details is called abstraction
(or) hiding internal implementation is called Abstraction We can enhance the internal
implementation without effecting outside world Abstraction provides security A class
contains lot of data and the user does not need the entire data The advantage of abstraction
is that every user will get his own view of the data according to his requirements and will
not get confused with unnecessary data A bank clerk should see the customer details like
account number, name and balance amount in the account He should not be entitled to see
the sensitive data like the staff salaries, profit or loss of the bank etc So such data can be
abstracted from the clerks view
eg: class Bank
{private int accno; private
String name; private
float balance;
private float profit;
private float loan;
void display_to_clerk ()
{
Systemoutprintln ("Accno = " + accno);
Systemoutprintln ("Name = " + name);
Systemoutprintln ("Balance = " + balance);
}
}
In the preceding class, inspite of several data items, the display_to_clerk () method is
able to access and display only the accno, name and balance values It cannot access profit
33
and loan of the customer This means the profit and loan data is hidden from the view of
the bank clerk
Inheritance: Acquiring the properties from one class to another class is called inheritance
(or) producing new class from already existing class is called inheritance Reusability of code
is main advantage of inheritance In Java inheritance is achieved by using extends keyword
The properties with access specifier private cannot be inherited
eg: class Parent
{
String parentName;
String familyName;
}
class Child extends Parent
{
String childName;
int childAge;
void printMyName()
{
Systemoutprintln (“My name is“+childName+” ”+familyName);
}
}
In the above example, the child has inherited its family name from the parent class just by
inheriting the class
Polymorphism: The word polymorphism came from two Greek words „poly‟ means
„many‟ and „morphos‟ means „forms‟ Thus, polymorphism represents the ability to assume
several different forms The ability to define more than one function with the same name is
called Polymorphism
eg:int add (int a, int b) float add
(float a, int b) float
add (int a , float b)
void add (float a)
int add (int a)
Message Passing: Calling a method in a class is called message passing We can call
methods of a class by using object with dot operator as:
object_namemethod_name ();
eg: sdisplay (); obadd (2, 5); obprintMyName ();
When the programmer does not initialize the instance variables, java compiler will write code
and initializes the variables with default values
Data Type Default Value
Int 0
Float 00
Double 00
Char Space
String null
Class null
Boolean false
s1display ();
Student s2 = new Student ();
Systemoutprintln ("Second Student Details : "
); s2display ();
}
}
Output:
Type 2: We can initialize one class instance variables in another class using reference
variable
srollNo = 101;
sname = “Kiran”;
.Output:
In this type of initialization the properties (variables in the class) are not available, if they
are declared as private
Access Specifiers: An access specifier is a key word that represents how to access a
member of a class There are four access specifiers in java
private: private members of a class are not available outside the class
public: public members of a class are available anywhere outside the
class o protected: protected members are available outside the class
o default: if no access specifier is used then default specifier is used by java compiler
Default members are available outside the class
{rollNo = r;
name = n;
}
}
A constructor does not return any value, not even void
37
.A constructor is called and executed at the time of creating an object o A constructor is called
only once per object
o Default constructor is used to initialize every object with same data where as
parameterized constructor is used to initialize each object with different data
o If no constructor is written in a class then java compiler will provide default values
. .
String name;
Student (int r, String n)
{rollNo = r;
name = n;
}
void display ()
{Systemoutprintln ("Student Roll Number is: " + rollNo);
Systemoutprintln ("Student Name is: " + name);
}
}
class StudentDemo
{public static void main(String args[])
{Student s1 = new Student (101, “Suresh”);
Systemoutprintln (“s1 object contains: “ );
s1display ();
Student s2 = new Student (102, “Ramesh”);
Systemoutprintln (“s2 object contains: “ );
s2display ();
}
}
Output:
The keyword ‘this’: There will be situations where a method wants to refer to the object
which invoked it To perform this we use „this‟ keyword There are no restrictions to use „this‟
keyword we can use this inside any method for referring the current object This keyword is
always a reference to the object on which the method was invoked We can use „this‟ keyword
wherever a reference to an object of the current class type is permitted „this‟ is a key word that
refers to present class object It refers to
Present class instance variables
Present class methods
Present class constructor
Program 6: Write a program to use „this‟ to refer the current class parameterized constructor
and current class instance variable
//this demo
class Person
{String name;
39
. .
Person ( )
{this (“Ravi Sekhar”); // calling present class parameterized constructor
thisdisplay ( ); // calling present class method
}
Person (String name)
{thisname = name; // assigning present class variable with parameter “name”
}
void display( )
{Systemoutprintln ("Person Name is = " + name);
}
}
class ThisDemo
{public static void main(String args[])
{
Person p = new Person ( );
}
}
Output:
Garbage Collection: Generally memory is allocated to objects by using „new‟ operator and
deleting an allocated memory is uncommon This deletion of memory is supported by delete
operator in C++ but this deletion of allocated memory works automatically in Java This
automatic deletion of already allocated but unused memory is called as garbage collection
This operation of garbage collection is accomplished by a method named “gc ()” This method
is used for garbage collection
The finalize( ) Method: It is possible to define a method that will be called just before an
object's final destruction by the garbage collector This method is called finalize( ) method To
add a finalizer to a class, simply define the finalize( ) method The Java runtime calls that
method whenever it is about to recycle an object of that class Inside the finalize( ) method
specify those actions that must be performed before an object is destroyed The finalize( )
method has this general form:
protected void finalize( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize ( ) by code defined
outside its class This means that you cannot know whenor even iffinalize ( ) will be executed
For example, if your program ends before garbage collection occurs, finalize ( ) will not
execute
40
Static Methods:
o Static methods can read and act upon static variables
o Static methods cannot read and act upon instance variables
o Static variable is a variable whose single copy is shared by all the objects
o Static methods are declared using keyword static
o Static methods can be called using objectnamemethodname (or) classnamemethodname
o From any object, if static variable is modified it affects all the objects Static variables are
stored on method area
Unit-II
Inheritance
Inheritance: Creating new class from existing class such that the features of existing class are
available to the new class is called inheritance Already existing class is called super class &
produced class is called sub class Using inheritance while creating sub classes a programmer
can reuse the super class code without rewriting it
Syntax: class subclass_name extends superclass_name
eg: class Child extends Parent
Program 1: Write a program to create a Person class which contains general details of a
person and create a sub class Employ which contains company details of a person Reuse the
general details of the person in its sub class
Inheritance
Example class Person
{String name;
String
permanentAddress; int
age;
void set_PermanentDetails (String name, String permanentAddress, int age)
{thisname = name; thispermanentAddress =
permanentAddress; thisage = age;
}
void get_PermanentDetails ()
{Systemoutprintln ("Name : " + name);
Systemoutprintln ("Permanent Address : " +
permanentAddress); Systemoutprintln ("Age :" + age);
}
}
class Employ extends Person
{int id;
String companyName;
String
companyAddress;
Employ (int id, String name, String permanentAddress, int age,
String companyName, String companyAddress)
{thisid = id;
set_PermanentDetails (name, permanentAddress, age);
thiscompanyName = companyName;
thiscompanyAddress = companyAddress;
}
void get_EmployDetails ()
{Systemoutprintln ("Employ Id : " + id);
get_PermanentDetails ();
Systemoutprintln ("Company Name : "+ companyName);
Systemoutprintln ("Company Address : "+companyAddress);
}
42
. .
}
class InherDemo
{public static void main (String args [])
{Employ e1 = new Employ (101, "Suresh Kumar", "18-Madhura Nagar-Tirupati", 29,
"Centris Software- Chennai", "20-RVS Nagar");
e1get_EmployDetails ();
}
}
Output:
Program 2: Write a program to illustrate the order of calling of default constructor in super
and sub class
Default constructors in super and sub
class class One
{ One ( ) //super class default constructor
{
Systemoutprintln ("Super class default constructor called");
}
}
class Two extends One
{ Two ( ) //sub class default constructor
{
Systemoutprintln ("Sub class default constructor called");
}
}
class Const
{public static void main (String args[])
}
Output:
43
Program 3: Write a program to access the super class method, super class parameterized
constructor and super class instance variable by using super keyword from sub class
super refers to super class- constructors, instance variables and
methods class A
{int x; A (int
x)
{
thisx = x;
}
void show( )
{Systemoutprintln("super class method: x = "+x);
}
}
class B extends A
{ int y;
B (int a,int b)
{
super(a) // (or) x=a;
;
y=b;
}
void show( )
{ supershow ();
Systemoutprintln ("y = "+y);
Systemoutprintln (“ super x = “ + superx);
}
}
class SuperUse
{
public static void main(String args[])
{B ob = new B (10, 24);
obshow ( );
}
}
44
. .
Output:
.
Polymorphism
Polymorphism came from the two Greek words „poly‟ means many and morphos means forms
If the same method has ability to take more than one form to perform several tasks then it is
called polymorphism It is of two types: Dynamic polymorphism and Static polymorphism
Dynamic Polymorphism: The polymorphism exhibited at run time is called dynamic
polymorphism In this dynamic polymorphism a method call is linked with method body at
the time of execution by JVM Java compiler does not know which method is called at the
time of compilation This is also known as dynamic binding or run time polymorphism
Method overloading and method overriding are examples of Dynamic Polymorphism in
Java o Method Overloading: Writing two or more methods with the same name, but with
a
difference in the method signatures is called method over loading Method signature
represents the method name along with the method parameters In method over loading
JVM understands which method is called depending upon the difference in the method
signature The difference may be due to the following:
There is a difference in the no of
parameters void add (int a,int b)
void add (int a,int b,int c)
There is a difference in the data types of
parameters void add (int a,float b)
void add (double a,double b)
There is a difference in the sequence of
parameters void swap (int a,char b)
void swap (char a,int b)
Program 1: Write a program to create a class which contains two methods with the same
name but with different signatures
overloading of methods --------- Dynamic
polymorphism class Sample
{void add(int a,int b)
{
Systemoutprintln ("sum of two="+ (a+b));
}
void add(int a,int b,int c)
{
Systemoutprintln ("sum of three="+ (a+b+c));
}
}
class OverLoad
{public static void main(String[] args)
{Sample s=new Sample ( ); sadd
(20, 25);
sadd (20, 25, 30);
}
}
46
Output:
Method Overriding: Writing two or more methods in super & sub classes with same
name and same signatures is called method overriding In method overriding JVM executes
a method depending on the type of the object
Program 2: Write a program that contains a super and sub class which contains a method
with same name and same method signature, behavior of the method is dynamically
decided //overriding of methods --------------- Dynamic polymorphism
class Animal
{ void move()
{
Systemoutprintln ("Animals can move");
}
}
class Dog extends Animal
{ void move()
{
Systemoutprintln ("Dogs can walk and run");
}
}
public class OverRide
{ public static void main(String args[])
{Animal a = new Animal (); // Animal reference and object
Animal b = new Dog (); // Animal reference but Dog
object amove (); // runs the method in Animal class
bmove (); //Runs the method in Dog class
}
}
Output:
Achieving method overloading & method overriding using instance methods is an example of
dynamic polymorphism
47
Type Casting: Converting one data type into another data type is called casting Type cast
operator is used to convert one data type into another data type Data type represents the type
of the data stored into a variable There are two kinds of data types:
Primitive Data type: Primitive data type represents singular values
eg: byte, short, int, long, float, double, char, boolean
48
Using casting we can convert a primitive data type into another primitive data type
This is done in two ways, widening and narrowing
Widening: Converting a lower data type into higher data type is called
widening byte, short, int, long , float, double
eg: char ch = 'a'; int
n = (int ) ch;
eg: int n = 12;
float f = (float) n;
Narrowing: Converting a higher data type into lower data type is called narrowing
eg: int i = 65;
char ch = (char)
i; eg: float f = 125;
int i = (int) f;
Referenced Data type: Referenced data type represents multiple values
eg: class, String
Using casting we can convert one class type into another class type if they are related
by means of inheritance
Generalization: Moving back from subclass to super class is called generalization or
widening or upcasting
Specialization: Moving from super class to sub class is called specialization or
narrowing or downcasting
Program 4: Write a program to convert one class type into another class type
conversion of one class type into another class
type class One
{void show1()
{Systemoutprintln ("One's method");
}
}
class Two extends One
{void show2()
{Systemoutprintln ("Two's method");
}
}
class Ex3
{
public static void main(String args[])
{
/* If super class reference is used to refer to super class object then only super class
members are available to programmer */
One ob1 = new One ();
ob1show1 ();
/* If sub class reference is used to refer to sub class object then super class members as
well as sub class members are available to the programmer */
Two ob2 = new Two();
ob2show1();
49
ob2show2();
/* If super class reference is used to refer to sub class object then super class methods
are available, sub class methods are not available unless they override super class
methods */
One ob3 = (One) new Two(); // Generalization
ob3show1();
/* It is not possible to access any methods if we use subclass object to refer to super
class as above */
Two ob4 = (Two) new One();
ob4show1();
ob4show2();
// Specialization
One ob5 = (One) new Two();
Two ob6 = (Two) ob5;
ob6show1();
ob6show2();
}
}
Note: Using casting it is not possible to convert a primitive data type into a referenced data
type and vice-versa For this we are using Wrapper classes
50
. .
Abstract Class
A method with method body is called concrete method In general any class will have all
concrete methods A method without method body is called abstract method A class that
contains abstract method is called abstract class It is possible to implement the abstract
methods differently in the subclasses of an abstract class These different implementations will
help the programmer to perform different tasks depending on the need of the sub classes
Moreover, the common members of the abstract class are also shared by the sub classes
The abstract methods and abstract class should be declared using the keyword abstract
We cannot create objects to abstract class because it is having incomplete code Whenever an
abstract class is created, subclass should be created to it and the abstract methods should be
implemented in the subclasses, then we can create objects to the subclasses
An abstract class is a class with zero or more abstract methods
An abstract class contains instance variables & concrete methods in addition to
abstract methods
It is not possible to create objects to abstract class
But we can create a reference of abstract class type
All the abstract methods of the abstract class should be implemented in its sub classes
If any method is not implemented, then that sub class should be declared as „abstract‟
Abstract class reference can be used to refer to the objects of its sub classes
Abstract class references cannot refer to the individual methods of sub classes
A class cannot be both „abstract‟ & „final‟
eg: final abstract class A // invalid
{ dim1 = a;
dim2 = b;
}
abstract double area ();
Wrapper Classes
Wrapper Classes are used to convert primitive data types into objects A wrapper class is a
class whose object wraps the primitive data type Wrapper classes are available in javalang
package Different applications on internet send data or recieve data in the form of objects The
classes in javautil package act upon objects only
Character Class: The Character class wraps a value of the primitive type char in an object
An object of type character contains a single field whose type is char We can create Character
class
52
Program 1: Write a program which shows the use of Character class methods
//Testing a char
import javaio*;
class CharTest
{public static void main(String args[]) throws IOException
{BufferedReader br = new BufferedReader (new InputStreamReader (Systemin));
Systemoutprint ("Enter a character : " );
char ch = (char) brread();
if (CharacterisDigit (ch) )
Systemoutprintln ("It is a digit");
else if (CharacterisUpperCase (ch)) Systemoutprintln
("It is a Upper Case Letter");
else if (CharacterisLowerCase (ch) )
Systemoutprintln ("It is a Lower Case
Letter");
else if ( CharacterisSpaceChar (ch))
Systemoutprintln ("It is a Space bar");
else if ( CharacterisWhitespace (ch) )
Systemoutprintln ("Dont know what is this character");
}
}
Output:
Constructors:
· Byte (byte num)
eg: Byte b1 = new Byte (98);
· Byte (String str)
eg: String str = "98";
Byte b2 = new Byte (str);
Methods of Byte Class:
Method Description
byte byteValue () returns the value of invoking object as a byte
This method is useful to compare the contents of two
int compareTo (Byte b)
Byte class objects
returns byte equivalent of the number contained in the
static byte parseByte(String str)
string specified by 'str'
returns a String that contains the decimal equivalent of
String toString ()
the invoking object
returns a Byte object that contains the value specified
static Byte valueOf (String str)
by the String 'str'
Program 2: Write a program which shows the use of Byte class methods
//Creating and comparing Byte Objects
import javaio*;
class Bytes
{public static void main(String args[]) throws IOException
{BufferedReader br = new BufferedReader (new InputStreamReader (Systemin));
Systemoutprint ("Enter a byte number: ");
String str = brreadLine ();
//convert str into Byte
object Byte b1 = new Byte
(str);
Systemoutprint ("Enter a another byte number:
"); str = brreadLine ();
//convert str into Byte obj
Byte b2 = BytevalueOf
(str); //compare b1 and b2
int n =
b1compareTo(b2); if
(n==0)
Systemoutprintln ("Both are Same");
else if(n>0)
Systemoutprintln (b1 + "is bigger");
else
Systemoutprintln (b2 + " is bigger");
}
}
Output:
54
Short Class: Short class wraps a value of primitive data type 'short' in its object Short class
object contains a short type field that stores a short number
Constructors:
· Short (short num)
· Short (String str)
Methods:
Method Description
This method compares the numerical value of two
int compareTo (Short obj)
Short class objects and returns 0,-ve, +ve value
This method compares the Short object with any other
Boolean equals ( Object obj)
object obj and returns true if both have same content
static short parseShort (String str) This method returns int equivalent of the String str
String toString () This method returns a String form of the Short object
This method converts a String str that contains a short
static Short valueOf (String str)
number into Short class object and returns that object
Integer Class: Integer class wraps a value of the primitive type 'int' in an object An object of
type Integer contains a single field whose type is int
Constructors:
· Integer (int num)
· Integer (String str)
Methods:
Method Description
int intVlaue () returns the value of the invoking object as an int
compares the numerical value of the invoking object
int compareTo (Integer obj)
with that of 'obj' returns zero or -ve value or +ve value
static int parseInt (String str) returns int equivalent of the String str
String toString () returns a String form of the invoking object
returns an Integer object that contains the value shown
static Integer valueOf (String str)
by str
returns a String representation of the integer argument
static String toBinaryString (int i)
in base2
returns a String representation of the integer argument
static String toHexString (int i)
in base 16
returns a String representation of the integer argument
static String toOctalString (int i)
in base 8
Float Class: Float class wraps a value of primitive type float in an object An object of type
float contains a single field whose type is float
Constructors:
· Float (float num)
55
Long Class: The Long class contains a primitive long type data The object of Long class
contains a field where we can store a long value
Constructors: Long has two constructors
Long (long num): Long object can be created as: Long obj = new Long (123000);
Long(String str): String str = "12300044";
Long obj = new Long (str);
Methods:
Method Description
This method compares the numerical value of two
int compareTo(Long obj)
Long class objects and returns ),-ve,+ve value
static long parseLong(String str) This method returns long equivalent of the String str
This method converts Long object into String object
String toString()
and returns the String object
This method converts a string str that contains some
Static Long valueOf(String str)
long number into Long object and returns that object
Boolean class: The Boolean class object contains a primitive 'boolean' type data The object of
Boolean class contains a field where we can store a boolean value
Constructors:
Boolean obj = new Boolean (true);
String str ="false";
Boolean obj = new Boolean (str);
Methods:
Method Description
This method compares the numerical value of two
int compareTo(Boolean obj)
Boolean class objects and returns 0,-ve,+ve value
This method returns boolean equivalent of the String
static boolean parseBoolean(String str)
str
String toString() This method converts Boolean object into a String
56
Double Class: Double class wraps a value of primitive type Double in an Object
Constructors:
· Double (double num)
· Double (String str)
Methods:
Method Description
double doubleValue() returns the value of the invoking object as a double
float floatValue() returns the value of the invoking object as a float
This method compares the numerical value of two
int compareTo(Double d)
Double class objects and returns 0,-ve,+ve value
static double parseDouble(String str) returns the double equivalent of the String str
This method converts Double object into a String
String toString()
object and returns the String object
returns the Double object with the value specified by
static Double valueOf(String str)
String str
57
Math class: The class Math contains methods for performing basic numeric operations
Methods:
Method Description
static double sin(double arg) returns the sine value of the arg arg is in radians
static double cos(double arg) returns the cosine value of the arg
static double tan(double arg) returns the tangent value of the arg
static double log(double arg) returns the natural logarithm value or arg
static double pow(double x, double n) returns x to the power of n value
static double sqrt(double arg) returns the square root of arg
static double abs(double arg) returns the absolute value of arg
returns the smallest integer which is greater or equal
to
static double ceil(double arg)
arg
returns the greatest integer which is lower or equal to
static double floor(double arg)
arg
static double min(arg1,arg2) returns the minimum of arg1 and arg2
static double max(arg1,arg2) returns the maximum of arg1 and arg2
static long round(arg) returns the rounded value of arg
static double random() returns a random number between 0 and 1
static double toRadians(double angle) converts angle in degrees into radians
static double toDegrees(double angle) converts angle in radians into degrees
Generic Types
Generic type represents classes, interfaces and methods in a type safe manner
Generic types can act on any type of data
All Generic types are subclasses of Object class, it acts on Objects only
Generic types act on advanced data type only
It is not possible to create an object to Generic type itself
Using generic types, we can avoid casting in many cases
Generic Class: When we create a class with an instance variable to store an Integer object, it
can be used to store Integer type data only We cannot use that instance variable to store a
Float class object or a String type Object To store different types of data into a class, we have
to write the same class again and again by changing the data type of the variables This can be
avoided using a generic class A generic class represents a class that is type-safe This means a
generic class can act upon any data type Generic classes and generic interfaces are also called
„parameterized types‟ because they use a parameter that determines which data type they
should work upon
Program 1: Write a program that has a class which stores any type of data
//Example for Generic Class
class MyClass<T>
{T obj; MyClass (T
obj)
{
thisobj = obj;
}
T getObj ()
{
return obj;
}
}
class Gen1
{public static void main(String args[])
{
Integer i1 = new Integer (10);
MyClass<Integer> obj1 = new
MyClass<Integer>(i1); Systemoutprintln ("U stored
: " + obj1getObj() );
Output:
Generic Method: We can make a method alone as generic method by writing the generic
parameter before the method return type as:
<T> returntype methodname ()
{
Method code;
}
eg: <T> void display_data ()
{
Method body;
}
Program 2: Write a program with generic method which displays any type of data
//Generic method example
class MyClass
{<T>void display_data (T arr[])
{
for (int i=0;i<arrlength; i++)
Systemoutprint ("\t" + arr[i]);
Systemoutprintln ();
}
}
class Gen2
{public static void main(String args[])
{MyClass obj = new MyClass ( ); Integer a[] =
{1,2,3,4,5,6}; Systemoutprint ("Reading
Integer Objects: "); objdisplay_data (a);
Output:
Generic Interface: It is possible to develop an interface using generic type concept The
general form of generic interface looks like:
interface interface_name <T>
{
//method that accepts any object
return_type method_name ( T object_name );
}
Here, T represents any data type which is used in the interface We can write an
implementation class for the above interface as:
class class_name <T> implements interface_name
<T> {
public return_type method_name ( T object_name )
{
//provide body of the method
}
}
. .
Output:
62
Interface
A programmer uses an abstract class when there are some common features shared by all the
objects A programmer writes an interface when all the features have different implementations
for different objects Interfaces are written when the programmer wants to leave the
implementation to third party vendors An interface is a specification of method prototypes All
the methods in an interface are abstract methods
An interface is a specification of method prototypes
An interface contains zero or more abstract methods
All the methods of interface are public, abstract by default
An interface may contain variables which are by default public static final
Once an interface is written any third party vendor can implement it
All the methods of the interface should be implemented in its implementation classes
If any one of the method is not implemented, then that implementation class should be
declared as abstract
We cannot create an object to an interface
We can create a reference variable to an interface
An interface cannot implement another interface
An interface can extend another interface
A class can implement multiple interfaces
Types of inheritance:
Single Inheritance: Producing subclass from a single super class is called single
inheritance
A A
class B extends
class B extends A A
class C extends
A
class D extends
B A
B C D
Multiple Inheritance: Producing subclass from more than one super class is called
Multiple Inheritance
Invalid in
A B A B C Java
class D extends A,
class C extends A, B
B, C class E extends
C A, B, C
D53 E
64
Java does not support multiple inheritance But multiple inheritance can be achieved by using
interfaces
Program 2: Write a program to illustrate how to achieve multiple inheritance using multiple
interfaces
//interface Demo
interface Father
{double PROPERTY = 10000;
double HEIGHT = 56;
}
interface Mother
{double PROPERTY = 30000;
double HEIGHT = 54;
}
class MyClass implements Father, Mother
{void show()
{ Systemoutprintln("Total property is :" +(FatherPROPERTY+MotherPROPERTY));
Systemoutprintln ("Average height is :" + (FatherHEIGHT + MotherHEIGHT)/2 );
}
}
class InterfaceDemo
{public static void main(String args[])
{MyClass ob1 = new MyClass();
ob1show();
}
}
Output:
65
Packages
A package is a container of classes and interfaces A package represents a directory that
contains related group of classes and interfaces For example, when we write statemens like:
import javaio*;
Here we are importing classes of javaio package Here, java is a directory name and io is
another sub directory within it The „*‟ represents all the classes and interfaces of that io sub
directory We can create our own packages called user-defined packages or extend the
available packages User-defined packages can also be imported into other classes and used
exactly in the same way as the Built-in packages Packages provide reusability
The –d option tells the Java compiler to create a separate directory and place the class file in
that directory (package) The () dot after –d indicates that the package should be created in the
current directory So, out package pack with Addition class is ready
}
Output:
Program 3: Write a program to add one more class Subtraction to the same package pack
//Adding one more class to package pack:
package pack;
public class Subtraction
{private double d1,d2;
public Subtraction(double a, double b)
{d1 = a; d2 =
b;
}
public void difference()
{Systemoutprintln ("Sum of two given numbers is : " + (d1 - d2) );
}
}
Compiling the above program:
Program 4: Write a program to access all the classes in the package pack
//To import all the classes and interfaces in a class using import pack*;
import pack*;
class Use
{public static void main(String args[])
{Addition ob1 = new Addition(105,206);
ob1sum();
Subtraction ob2 = new
Subtraction(302,4011); ob2difference();
}
}
In this case, please be sure that any of the Additionjava and Subtractionjava programs will not
exist in the current directory Delete them from the current directory as they cause confusion
for the Java compiler The compiler looks for byte code in Additionjava and Subtractionjava
files and there it gets no byte code and hence it flags some errors
67
Output:
If the package pack is available in different directory, in that case the compiler should be given
information regarding the package location by mentioning the directory name of the package in
the classpath The CLASSPATH is an environment variable that tells the Java compiler where to
look for class files to import If our package exists in e:\sub then we need to set class path as
follows:
We are setting the classpath to e:\sub directory and current directory () and
%CLASSPATH% means retain the already available classpath as it is
Creating Sub package in a package: We can create sub package in a package in the format:
package packagenamesubpackagename;
eg: package pack1pack2;
Here, we are creating pack2 subpackage which is created inside pack1 package To use the
classes and interfaces of pack2, we can write import statement as:
import pack1pack2;
Access Specifier: Specifies the scope of the data members, class and methods
private members of the class are available with in the class only The scope of private
members of the class is “CLASS SCOPE”
68
public members of the class are available anywhere The scope of public members of the
class is "GLOBAL SCOPE"
default members of the class are available with in the class, outside the class and in its sub
class of same package It is not available outside the package So the scope of default
members of the class is "PACKAGE SCOPE"
protected members of the class are available with in the class, outside the class and in its
sub class of same package and also available to subclasses in different package also
Class Member Access private No Modifier protected public
Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No No Yes Yes
Different package non-subclass No No No Yes
Inner Class
Inner Class: A class with in another class is called Inner class When the programmer wants to
restrict the access of entire code of a class, creates an inner class as a private class The way to
access the inner class is through its outer class only
· Inner class is a safety mechanism
· Inner class is hidden in outer class from other classes
· Only inner class can be private
· An object to Inner class can be created only in its outer class
· An object to Inner class cannot be created in any other class
· Outer class object and Inner class objects are created in separate memory locations
· Outer class members are available to Inner class object
· Inner class object will have an additional invisible field called „this$0‟ that stores a reference
of outer class object
· Inner class members are referenced as: thismember;
· Outer class members are referred as: Outerclassthismember;
Program 3: Write a program to access private members of a class using inner class
// inner class demo
class Bank
{ private double bal, rate;
Bank (double b, double r)
{ bal=b;
rate = r;
}
void display ( )
{ Interest in=new Interest ();
incalculateInterest ( );
Systemoutprintln ("New Balance : " + bal);
}
private class Interest
{ void calculateInterest ( )
{ Systemoutprintln ("Balance = "+ bal);
double interest=bal* rate/100;
Systemoutprintln ("interest = "+interest);
bal+=interest;
}
}
}
class InnerDemo
{ public static void main (String args[])
{ Bank account = new Bank (20000, 5);
accountdisplay ();
}
}
71
UNIT-III
Applets
An applet is a program that comes from server into a client and gets executed at client side
and displays the result An applet represents byte code embedded in a html page (applet =
bytecode
html) and run with the help of Java enabled browsers such as Internet Explorer An applet is
a Java program that runs in a browser Unlike Java applications applets do not have a main ()
method To create applet we can use javaappletApplet or javaxswingJApplet class All applets
inherit the super class „Applet‟ An Applet class contains several methods that helps to control
the execution of an applet
Advantages:
Applets provide dynamic nature for a webpage
Applets are used in developing games and animations
Creating an applet:
Let the Applet class extends Applet or JApplet class
Overide the following methods of Applet class
o public void init (): This method is used for initializing variables, parameters to create
components This method is executed only once at the time of applet loaded into
memory
o public void start (): After init() method is executed, the start method is executed
automatically Start method is executed as long as applet gains focus In this method
code
related to opening files and connecting to database and retrieving the data and
processing the data is written
public void stop (): This mehtod is executed when the applet loses focus Code related to
closing the files and database, stopping threads and performing clean up operations are
written in this stop method
public void destroy (): This method is exexuted only once when the applet is terminated
from the memory
Executing above methods in that sequence is called applet life cycle We can also use
public void paint (Graphics g) in applets
After writing an applet, an applet is compiled in the same way as Java application but running
of an applet is different There are two ways to run an applet
Executing an applet within a Java compatible web browser
Executing an applet using „appletviewer‟ This executes the applet in a window
To execute an applet using web browser, we must write a small HTML file which contains the
appropriate „APPLET‟ tag <APPLET> tag is useful to embed an applet into an HTML page It
has the following form:
<APPLET CODE=”name of the applet class file” CODEBASE=”path of the applet class file”
HEIGHT = maximum height of applet in pixels WIDTH = maximum width of
applet in pixels ALIGN = alignment (LEFT, RIGHT, MIDDLE, TOP, BOTTOM)
ALT = alternate text to be displayed>
<PARAM NAME = parameter name VALUE = its
value> </APPLET>
72
The <PARAM> tag useful to define a variable (parameter) and its value inside the HTML
page which can be passed to the applet The applet can access the parameter value using
getParameter () method, as:
String value = getParameter (“pname”);
Where pname is the parameter name and its value is retrieved
The HTML file must be saved with html extension After creating this file, open the Java
compatible browser (Internet Explorer) and then load this file by specifying the complete path,
then Applet program will get executed
In order to execute applet program with an applet viewer, simply include a comment at the
head of Java Source code file that contains the „APPLET‟ tagThus, our code is documented
with a prototype of the necessary HTML statements and we can test out compiled applet by
starting the
appletviewer with the Java file as: appletviewer programnamejava
Program 1: Write an applet program with a message and display the message in paint ()
method
/* <applet code="MyAppletclass" width = 600 height= 450>
</applet> */
import javaappletApplet;
import javaawt*;
public class MyApplet extends Applet
{String msg=""; public
void init()
{
msg += "init";
}
public void start()
{
msg +=" start";
}
public void paint(Graphics g)
{
gdrawString(msg,10,100);
}
public void stop()
{
msg += " stop";
}
public void destroy()
{
msg+= " destroy";
}
}
Output:
73
. .
Program 2: Write a program to move an image from left to right in an Applet To load an
image use Image class of javaawt
/* <applet code="MyApplet1class" width = 600 height= 450>
</applet> */
import javaapplet*;
import javaawt*;
public class MyApplet1 extends Applet
{public void paint (Graphics g)
{Image i = getImage (getDocumentBase (),"planegif"); for
(int x= 0 ; x<=800 ; x++)
{gdrawImage (i, x, 0, null); try
{Threadsleep (20);
}
catch(InterruptedException ie) { }
}
}
}
Output:
74
EXCEPTION HANDLING
An error in a program is called bug Removing errors from program is called debugging There
are basically three types of errors in the Java program:
Compile time errors: Errors which occur due to syntax or format is called compile time
errors These errors are detected by java compiler at compilation time Desk checking is
solution for compile-time errors
Runtime errors: These are the errors that represent computer inefficiency Insufficient
memory to store data or inability of the microprocessor to execute some statement is
examples to runtime errors Runtime errors are detected by JVM at runtime
Logical errors: These are the errors that occur due to bad logic in the program These
errors are rectified by comparing the outputs of the program manually
Object
|
Throwable
|
Error Exception
eg: AWTError eg: (CheckedException,
UnCheckedException
VirtualMachineError )
LinkageError
An exception can be handled by the programmer where as an error cannot be handled by the
programmer When there is an exception the programmer should do the following tasks:
If the programmer suspects any exception in program statements, he should write them
inside try block
try
{
statements;
}
When there is an exception in try block JVM will not terminate the program abnormally
JVM stores exception details in an exception stack and then JVM jumps into catch block
The programmer should display exception details and any message to the user in catch
block
76
Program 1: Write a program which tells the use of try, catch and finally block
Exception example
class
ExceptionExample
{public static void main(String args[])
{try
{Systemoutprintln ("open files"); int
n=argslength; Systemoutprintln
("n="+n); int a=45/n;
Systemoutprintln ("a="+a);
int b[]={10,19,12,13};
b[50]=100;
}
catch (ArithmeticException ae)
{Systemoutprintln ("ae");
Systemoutprintln ("plz type data while executing the program");
}
catch (ArrayIndexOutOfBoundsException aie)
{Systemoutprintln ("aie");
Systemoutprintln ("please see that array index is not within the range");
}
finally
{ Systemoutprintln ("close files");
}
}
}
Output:
77
.Even though multiple exceptions are found in the program, only one exception is raised at a
time.We can handle multiple exceptions by writing multiple catch blocks.A single try block
can be followed by several catch blocks.Catch block does not always exit without a try, but a
try block exit without a catch block.Finally block is always executed whether there is an
exception or not
throws Clause: throws clause is useful to escape from handling an exception throws clause is
useful to throw out any exception without handling it
throw Clause: throw clause can be used to throw out user defined exceptions It is useful to
create an exception object and throw it out of try block
}
catch (NullPointerException ne)
{
Systemoutprintln ("ne");
}
78
}
public static void main(String args[])
{
ThrowDemoDemo ( );
}
}
Output:
Types of Exceptions:
Built-in exceptions: These are the exceptions which are already available in java
eg: ArithmeticException, ArrayIndexOutOfBoundsException,
NullPointerException, StringIndexOutOfBoundsException,
NoSuchMethodException, InterruptedException, ClassNotFoundException,
FileNotFoundException, NumberFormatException, RuntimeException etc
User-defined exceptions: - These are the exceptions created by the programmer
Threads
thread Thread is a smallest unit of code Thread is also defined as a subprocess A Thread
sometimes called an execution context or a light weight process
Uses of Threads:
Threads are used in designing serverside programs to handle multiple clients at a time
Threads are used in games and animations
Creating a Thread:
Write a class that extends Thread class or implements Runnable interface this is available
in lang package
Write public void run () method in that class This is the method by default executed by
any thread
Create an object to that class
Create a thread and attach it to the object
Start running the threads
class TDemo
{public static void main(String args[])
{MyThread obj = new MyThread ();
Thread t = new Thread (obj);
tstart ();
}
}
Output:
Multi Tasking Using Threads: In multi tasking, several tasks are executed at a time For this
purpose, we need more than one thread For example, to perform 2 tasks we can take 2 threads
and attach them to the 2 tasks Then those tasks are simultaneously executed by the two
threads Using more than one thread is called „multi threading‟
}
Output:
In the preceding example, we have used 2 threads on the 2 objects of TDemo1 class
First we have taken a String variable str in Theatre class Then we passed two strings- cut
ticket and show chair into that variable from TDemo1 class When t1 start () is executed, it
starts execution run () method code showing cut ticket Note that in run () method, we used:
Thread sleep (2000) is a static method in Thread class, which is used to suspend execution of
a thread for some specified milliseconds Since this method can throw InterruptedException,
we caught it in catch block When Thread t1 is suspended immediately t2 start () will make the
thread t2 to execute and when it encounters Threadsleep(2000), it will suspend for specified
time meanwhile t1 will get executed respectively In this manner, both the threads are
simultaneously executed
Multiple Threads Acting on Single Object: When two people (threads) want to perform
same task then they need same object (run () method) to be executed each time Take the case
of railway reservation Every day several people want reservation of a berth for them The
procedure to reserve the berth is same for all the people So we need some object with same
run () method to be executed repeatedly for all the people (threads)
Let us think that only one berth is available in a train and two passengers (threads) are
asking for that berth in two different counters The clerks at different counters sent a request to
the server to allot that berth to their passengers Let us see now to whom that berth is allotted
Program 4: Write a program to create multiple threads and make the threads to act on single
object
//Multiple Threads acting on single object
class Reserve implements Runnable
{int available = 1; int
wanted;
Reserve (int i)
{wanted = i;
}
public void run()
{synchronized (this)
83
class Safe
{public static void main(String args[])
{Reserve obj = new Reserve (1);
Thread t1 =new Thread (obj);
Thread t2 = new Thread (obj);
t1setName ("First Person");
t2setName ("Second Person");
t1start ();
t2start ();
}
}
Output:
If we would not use synchronized (this) block in the preceding program then when
thread t1 enter into the run () method, it sees available number of berths as 1 and hence it
allots it to First Person and displays “1 Berths reserved for First Person” Then it enters try { }
block inside run () method, where it will sleep for 2 seconds In this time, the ticket will be
printed on the printer When the first thread is sleeping thread t2 also enters the run () method,
it also sees that there is 1 berth remaining The reason is for this is that the available number of
berths is not yet updated by the first thread So the second thread also sees 1 berth as available
and it allots the same berth to the Second Person Then the thread t2 will also go into sleep
state Thread t1 wakes up first and then it updates the available number of berths to zero (0)
But at the same time the second thread has already allotted the same berth to the Second
84
Person also Since both the threads are acting on the same object simultaneously, the result will
be unreliable
}
.
Deadlock: When a Thread locked an object and waiting for another object to be released by
another Thread, and the other thread is also waiting for the first thread to release the first
object, both the threads will continue waiting forever This is called "Thread Deadlock"
85
Even if we synchronize the threads, there is possibility of other problems like deadlock
Daily, thousands of people book tickets in trains and cancel tickets also If a programmer is to
develop code for this, he may visualize that booking tickets and canceling them are reverse
procedures Hence, he will write these 2 tasks as separate and opposite tasks and assign 2
different threads to do these tasks simultaneously
To book a ticket, the thread will enter the train object to verify that the ticket is
available or not When there is a ticket, it updates the available number of tickets in the train
object For this, it takes say 150 milli seconds Then it enters the compartment object In
compartment object, it should allot the ticket for the passenger and update its status to
reserved This means the thread should go through both the train and compartment objects
Similarly, let us think if a thread has to cancel a ticket, it will first enter compartment object
and updates the status of the ticket as available For this it is taking say 200 milliseconds Then
it enters train object and updates the available number of tickets there So, this thread
alsoshould fo through both the compartment and train objects
When the BookTicket thread is at train object for 150 milliseconds, the CancelTicket
thread will be at compartment object for 200 milliseconds Because we are using multiple
(more than one) threads, we should synchronize them So, the threads will lock those objects
When 150 milliseconds time is over, BookTicket thread tries to come out of train object and
wants to lock on compartment object, by entering it At that time, it will find that the
compartment object
is already locked by another thread (CancelTicket) and hence it will wait BookTicket thread
will wait for compartment object for another 50 milli seconds
After 200 milliseconds time is up, the CancelTicket thread which is in compartment
object completes its execution and wants to eneter and lock on train object But it will find that
the train object is already under lock by BookTicket thread and hence is not available Now,
CancelTicket will wait for the train object which should be unlocked by BookTicket
In this way, BookTicket thread keeps on waiting for the CancelTicket thread to unlock the
compartment object and the CancelTicket thread keeps on waiting for the BookTicket to
unlock the train object Both the threads will wait forever in this way, this situation is called
DealLock
{thistrain = train;
thiscomp = comp;
}
public void run()
{synchronized (train)
{
Systemoutprintln ("Book ticket has locked on train");
. .
try
{
Threadsleep (2000);
}
catch (InterruptedException ie)
{
}
Systemoutprintln ("Book ticket tries to lock train object");
synchronized (comp)
{
Systemoutprintln ("Book ticket has locked compartment");
}
}
}
}
class Dead
{public static void main (String args[])
{Object train = new Object ();
Object compartment = new Object ();
CancelTicket obj1 = new CancelTicket (train, compartment);
BookTicket obj2 = new BookTicket (train, compartment);
Thread t1 = new Thread (obj1);
Thread t2 = new Thread (obj2);
t1start ();
t2start ();
}
}
87
Output:
There is no specific solutioin for preventing deadlock The programmer should exercise
proper caution while planning the logic of the program to avoid deadlocks
Thread Communication: In some cases two or more threads should communicate with each
other One thread output may be send as input to other thread For example, a consumer thread
is waiting for a Producer to produce the data (or some goods) When the Producer thread
completes production of data, then the Consumer thread should take that data and use it
In producer class we take a StringBuffer object to store data, in this case; we take some
numbers from 1 to 5 These numbers are added to StringBuffer object Until producer
completes placing the data into StringBuffer the consumer has to wait Producer sends a
notification immediately after the data production is over
{ synchronized (prodsb)
{ try
{
prodsbwait ();
}
catch (Exception e) {
Systemoutprintln (prodsb);
}
}
class Communicate
t2start ();
t1start ();
}
catch (Exception e) {
Systemoutprintln (prodsb);
}
}
89
Output:
Both sleep () and wait () methods are used to suspend a thread execution for a specified time
When sleep () is executed inside a synchronized block, the object is still under lockWhen wait
() method is executed, it breaks the synchronized block, so that the object lock is removed and
it is available
Thread Group: A ThreadGroup represents a group of threads The main advantage of taking
several threads as a group is that by using a single method, we will be able to control all the
threads in the group
· Creating a thread group: ThreadGroup tg = new ThreadGroup
(“groupname”);
· To add a thread to this group (tg): Thread t1 = new Thread (tg, targetobj,
“threadname”);
To add another thread group to this group (tg):
ThreadGroup tg1 = new ThreadGroup (tg,
“groupname”);
· To know the parent of a thread: tggetParent ();
· To know the parent thread group: tgetThreadGroup ();
This returns a ThreadGroup object to which the thread t belongs
· To know the number of threads actively running in a thread group: tactiveCount ();
· To change the maximum priority of a thread group tg: tgsetMaxPriority ();
Thread States (Life-Cycle of a Thread): The life cycle of a thread contains several states At
any time the thread falls into any one of the states
A thread enters the dead state when its run () method completes (or) terminates for any
reason A dead thread is eventually be disposed of by the system
One common way for a running thread to enter the blocked state is when the thread issues
an input or output request In this case a blocked thread becomes ready when the input or
output waits for completes A blocked thread can‟t use a processor even if one is available
UNIT-IV
ABSTRACT WINDOW TOOLKIT
Container
Panel Applet
A window represents a box shaped area on the screen Window does not have border and title
A Frame is a top level window that is not contained in another window A Frame contains
border and title
Creating the Frame:
· We can create a Frame by creating Frame class object Frame obj = new Frame ();
(or)
Create a class that extends Frame class then create an object to that class
class MyClass extends Frame
92
//creating a Frame
import javaawt*;
class MyFrame
{
public static void main(String args[])
{Frame f1 = new Frame ();
f1setSize (500,150);
f1setTitle ("GUI World");
f1setVisible (true);
}
}
Output:
The frame can be minimized, maximized and resized but cannot be closed Even if we click on
close button of the frame, it will not perform any closing action Closing a frame means
attaching action to the component To attach actions to the components, we need „Event
Delegation Model‟
Closing the Frame: We know Frame is also a component We want to close the frame by
clicking on its close button Let us follow these steps to see how to use event delegation model
to do this:
We should attach a listener to the frame component Remember, all listeners are available
in javaawtevent package The most suitable listener to the frame is „WindowListener‟ It
can be attached using addWindowListener () method as:
faddWindowListener (WindowListener obj);
Please note that the addWindowListener () method has a parameter that is expecting object
of WindowListener interface Since it is not possible to create an object to an interface, we
should create an object to the implementation class of the interface and pass it to the
method
Implement all the methods of the WindowListener interface The following methods are
found in WindowListener interface:
public void windowActivated (WindowEvent e)
public void windowClosed (WindowEvent e)
public void windowClosing (WindowEvent e)
public void windowDeactivated (WindowEvent
e)
public void windowDeiconified (WindowEvent e)
public void windowIconified (WindowEvent e)
public void windowOpened (WindowEvent e)
In all the preceding methods, WindowListener interface calls public void windowClosing (
)
method when the frame is being closed So, implementing this method alone is enough, as:
public void windowClosing (WindowEvent e)
{ //Close the application
Systemexit (0);
}
95
So, when the frame is closed the body of this method is executed and the application gets
closed In this way, we can handle the frame closing event
An adapter class is an implementation class of a listener interface which contains all methods
implemented with empty body For example, WindowAdapter is an adapter class of
WindowListener interface WindowAdapter in javaawtevent package contains all the methods
of the WindowListener interface with an empty implementation (body) If we can extend
MyClass from this WindowAdapter class, then we need not write all the methods with empty
implementation We can write only that method which we are in need
The code of MyClass can be copied directly into addWindowListener () method, as:
f1addWindowListener (new WindowAdapter ()
{
public void windowClosing(WindowEvent e)
{
Systemexit (0);
96
}
});
We cannot find the name of MyClass anywhere in the code It means the name of MyClass is
hidden in MyFame class and hence MyClass is an inner class in MyFrame class whose name
is not mentioned Such an inner class is called „anonymous inner class‟ An anonymous inner
class is an inner class whose name is not written and for which only one object is created A
class for which only one object is created is called singleton class
Displaying text in the Frame: We need paint () method whenever we want to display some
new drawing or text or images in the Frame The paint () method is automatically called when
a frame is created and displayed The paint () method refreshes the frame contents
automatically when a drawing is displayed The paint () method takes Graphics Class object as
parameter Gaphics class is present in javaawt package
To display some text or strings in the frame, we can take the help of drawstring () method
of Graphics class as:
gdrawString (“Hai Readers”, x, y);
Here, the string “Hai Readers” will be displayed starting from the coordinates (x, y)
If we want to set some color for the text, we can use setColor () method of Graphics class
as: gsetColor (Colorred);
The first way is by directly mentioning the needed standard color name from Color class
as Colorblack, Colorblue, Colorcyan, Colorpink, Colorred, Colororange,
Colormagenta, ColordarkGray, Colorgray, ColorlightGray, Colorgreen, Coloryellow
and Colorwhite etc
The second way to mention any color is by combining the three primary colors: red,
green and blue while creating Color class object as:
Color c = new Color (r, g, b);
Here, r, g, b values can change from 0 to 255 0 represents no color 10 represent low
intensity whereas 200 represent high intensity of color
eg: Color c = new Color (255, 0, 0); //red color
To set some font to the text, we can use setFont () method of Graphics class, as:
gsetFont (Font object);
This method taked Font class object, which can be created as:
Font f = new Font (“SansSerif”, FontBOLD, 30);
Here, “SansSerif” represents the font name; FontBOLD represents the font style and
30 represents the font size in pixels
Systemexit (0);
}
});
}
public static void main (String args[])
{Message m = new Message ();
msetTitle ("Simple
Message"); msetSize
(650,150); msetVisible (true);
}
public void paint (Graphics g)
{thissetBackground (Colorgreen);
gsetColor (Colorred);
Font f = new Font ("Times New Roman", FontBOLD+FontITALIC,
60); gsetFont (f);
gdrawString ("Hello Readers!”, 50, 100);
}
}
Output:
Drawing in the Frame: Graphics class of javaawt package has the following methods which
help to draw various shapes
drawLine (int x1, int y1,int x2, int y2): to draw a line connecting (x1, y1) and (x2, y2)
drawRect (int x, int y, int w, int h): draws outline of the rectangle, rectangles top left
corner starts at (x, y) the width is w and height is h
drawRoundRect (int x, int y, int w, int h, int arcw, int arch): draws the outline of the
rectangle with rounded corners Rectangles top left corner starts at (x, y) the width is w and
height is h The rounding is specified by arcw and arch
drawOval (int x, int y, int w, int h): This method draws a circle or ellipse
drawArc(int x, int y, int w, int h, int sangle, int aangle): draws an arc where sangle stands
for starting angle and aangle stands for ending angle
. .
98
drawPolygon (int x[], int y[], int n): This method draws a polygon that connects pairs of
coordinates Here, x[] is an array which holds x coordinates of points and y[] is an array
which holds y coordinates, n represents the number of pairs of coordinates
To fill any shape with a desired color, first of all we should set a color using setColor ()
method
Then any of the following methods will draw those respective shapes by filling with the color
fillRect (int x, int y, int w, int h): Draws a rectangle and fills it with the specified color
drawRoundRect (int x, int y, int w, int h, int arcw, int arch): Draws filled rectangle with
rounded corners
drawOval (int x, int y, int w, int h): Draws filled oval with a specified color
drawArc(int x, int y, int w, int h, int sangle, int aangle): Draws an arc and fills it with a
specified color
drawPolygon (int x[], int y[], int n): Draws and fills a polygon with a specified color
. .
. .
Method Description
Font getFont () This method returns the font of the component
void setFont (Font f) This method sets a particular font f for the text of the
component
Color getForeground () This method gives the foreground color of the component
void setForeground (Color c) This method sets a foreground color c to the component
Color getBackground () Gets the background color of the component
void setBackground (Color c) Sets the background color c for the component
String getName () Returns the name of the component
void setName (String name) Sets a new name for the component
int getHeight () Returns the height of the component in pixels as an integer
int getWidth () Returns the width of the component in pixels as an integer
Dimension getSize () Returns the size of the component as an object of
Dimension class Dimensionwidth and Dimensionheight
will provide the width and height of the component
int getX () Returns the current x coordinate of the components origin
int getY () Returns the current y coordinate of the components origin
Point getLocation () Gets the locationof the component in the form of a point
specifying the components top-left corner
void setLocation (int x, int y) Moves the component to a new location specified by (x, y)
void setSize(int width, int height) Resizes the component so that it has new width and height
as passed to setSize () method
void setVisible (boolean b) Shows the component if the value of b is true or hides the
component if the value of parameter b is false
void setEnabled (boolean b) Enables the component if the value of b is true or disables
the component if the value of parameter b is false
void setBounds (int x, int y, int w, This method allots a rectangular area starting at (x ,y)
int h) coordinates and with width w and height h The component
is resized to this area before its display This method is
useful to specify the location of the component in the frame
After creating a component, we should add the component to the frame For this purpose, add
() method is used fadd (component); where f is frame class object
Similarly, to remove a component from the frame, we can use remove () method as:
fremove (component); where f is frame class object
Frame class contains a method called setLayout () setLayout () is useful to set a layout for
the frame A layout represents a manner of arranging components in the frame All layouts
are represented as implementation classes of LayoutManager interface For example, the
following layouts are available in AWT:
o FlowLayout: FlowLayout is useful to arrange the components in a line after the other
When a line is filled with components, they are automatically placed in the next line
o BorderLayout: BorderLayout is useful to arrange the components in the 4 borders of the
frame as well as in the center The borders are specified as South, North, East, West
and Center
o CardLayout: A cardLayout treats each component as a card Only one card is visible at a
time and it arranges the components as a stack of cards
. .
102
GridLayout: It is useful to divide the display area into a two dimensional grid form that
contains several rows and columns The display area is divided into equal sized
rectangles and one component is placed in each rectangle
GridBagLayout: This layout is more flexible as compared to other layouts since in this
layout the components can span more than one row or column and the size of the
components can be adjusted to fit the display area
We will discuss about layout manager in later chapter The following points are helpful to
understand how to work with a layout manager:
To set a layout for out components, we can pass the layout class object to the setLayout ()
method as: setLayout (new FlowLayout ());
Suppose, we do not want to set any layout, then we should pass null to the setLayout ()
method as: setLayout (null);
Suppose, we do not use setLayout () method at all, then the Java compiler assumes a default
layout manager The default layout in case of a frame is BorderLayout
Listeners and Listener Methods: Listeners are available for components A Listener is an
interface that listens to an event from a component Listeners are available in javaawtevent
package The methods in the listener interface are to be implemented, when using that listener
Component Listener Listener methods
Button ActionListener public void actionPerformed (ActionEvent e)
Checkbox ItemListener public void itemStateChanged (ItemEvent e)
CheckboxGroup ItemListener public void itemStateChanged (ItemEvent e)
TextField ActionListener public void actionPerformed (ActionEvent e)
FocusListener public void focusGained (FocusEvent e)
public void focusLost (FocusEvent e)
TextArea ActionListener public void actionPerformed (ActionEvent e)
FocusListener public void focusGained (FocusEvent e)
public void focusLost (FocusEvent e)
Choice ActionListener public void actionPerformed (ActionEvent e)
ItemListener public void itemStateChanged (ItemEvent e)
List ActionListener public void actionPerformed (ActionEvent e)
ItemListener public void itemStateChanged (ItemEvent e)
Scrollbar AdjustmentListener public void
MouseMotionListener adjustmentValueChanged (AdjustmentEvent e)
public void mouseDragged (MouseEvent e)
public void mouseMoved (MouseEvent e)
Label No listener is needed
Creating Push Buttons: Button class is useful to create push buttons A push button triggers a
series of events
· To create push button: Button b1 =new Button("label");
· To get the label of the button: String l = b1getLabel();
· To set the label of the button: b1setLabel("label");
String str =
· To get the label of the button clicked: aegetActionCommand();
where ae is object of ActionEvent
103
. .
Checkbox: A Checkbox is a square shapped box which provides a set of options to the user
· To create a Checkbox: Checkbox cb = new Checkbox ("label");
To create a checked Checkbox: Checkbox cb = new Checkbox ("label", null, true);
To get the state of a Checkbox: boolean b = cbgetState ();
To set the state of a Checkbox: cbsetState (true);
To get the label of a Checkbox: String s = cbgetLabel ();
Radio Button: A Radio button represents a round shaped button such that only one can be
selected from a panel Radio button can be created using CheckboxGroup class and Checkbox
classes
· To create a radio button: CheckboxGroup cbg = new CheckboxGroup ();
Checkbox cb = new Checkbox ("label", cbg,
true);
To know the selected
· checkbox: Checkbox cb = cbggetSelectedCheckbox ();
To know the selected checkbox label: String label = cbggetSelectedCheckbox ()getLabel
();
Choice Menu: Choice menu is a popdown list of items Only one item can be selected
· To create a choice menu: Choice ch = new Choice();
· To add items to the choice menu: chadd ("text");
To know the name of the item selected from the choice menu:
String s = chgetSelectedItem ();
· To know the index of the currently selected item: int i = chgetSelectedIndex(); This
method returns -1, if nothing is selected
. .
obsetVisible (true);
}
}
Output:
List box: A List box is similar to a choice box, it allows the user to select multiple items
· To create a list box: List lst = new List();
(or)
List lst = new List (3, true);
This list box initially displays 3 items The next parameter true represents that the user can
select more than one item from the available items If it is false, then the user can select only
one item
· To add items to the list box: lstadd("text");
String x[] =
· To get the selected items: lstgetSelectedItems();
· To get the selected indexes: int x[] = lstgetSelectedIndexes ();
chadd ("Bangladesh");
add (ch);
chaddItemListener (this);
addWindowListener (new WindowAdapter ()
{public void windowClosing (WindowEvent we)
{Systemexit (0);
}
});
}
public void itemStateChanged (ItemEvent ie)
{repaint ();
}
public void paint (Graphics g)
{try
{gdrawString ("U Selected:", 20, 150); msg
= chgetSelectedIndexes ();
for (int i =0;i<msglength; i++)
{String item = chgetItem (msg[i]);
gdrawString (item, 100, 150+i*20);
}
}catch (NullPointerException ie){}
}
public static void main (String args[])
{MyList ob = new MyList ();
obsetSize (500,200);
obsetTitle ("List Demo");
obsetVisible (true);
}
}
Output:
110
. .
TextArea: TextArea is similar to a TextField, but it accepts more than one line of text
To create a TextArea: TextArea ta = new TextArea(); (or)
Scrollbar Class: Scrollbar class is useful to create scrollbars that can be attached to a frame or
text area Scrollbars can be arranged vertically or horizontally
To create a scrollbar :Scrollbar sb = new Scrollbar (alignment, start, step, min, max);
alignment: ScrollbarVERTICAL, ScrollbarHORIZONTAL
start: starting value (eg 0)
step: step value (eg 30) // represents scrollbar length
min: minimum value (eg 0)
max: maximum value (eg 300)
· To know the location of a scrollbar: int n = sbgetValue ();
· To update scrollbar position to a new position: sbsetValue (int position);
int x = sbgetMaximum
· To get the maximum value of the scrollbar: ();
· To get the minimum value of the scrollbar: int x = sbgetMinimum ();
· To get the alignment of the scrollbar: int x = getOrientation ();
This method return 0 if the scrollbar is aligned HORIZONTAL, 1 if aligned VERTICAL
Program 13: Write a program to create a vertical scrollbar with scroll button length 30 px and
with the starting and ending positions ranging from 0 to 400 px //Creating a vertical scrollbar
import javaawt*;
112
import javaawtevent*;
class MyScroll extends Frame implements AdjustmentListener
{String msg = "";
Scrollbar sl;
MyScroll ()
{setLayout (null);
sl = new Scrollbar (ScrollbarVERTICAL, 0, 30, 0, 400);
slsetBounds (250, 50, 30, 200);
add (sl); sladdAdjustmentListener (this);
addWindowListener (new WindowAdapter ()
Handling Mouse Events: The user may click, release, drag or move a mouse while
interacting with the application If the programmer knows what the user has done, he can write
the code according to the mouse event To trap the mouse events, MouseListener and
MouseMotionListener interfaces of javawtevent package are used MouseListener interface
contains the following methods:
Method Description
This method is invoked when the mouse
public void mouseClicked (MouseEvent me) button
has been clicked on a component
This method is invoked when the mouse
public void mousePressed (MouseEvent me) button
has been pressed on a component
This method is invoked when the mouse
public void mouseReleased (MouseEvent me) button
has been released on a component
public void mouseEntered (MouseEvent me) This method is invoked when the mouse enters
a component
This method is invoked when the mouse exits
public void mouseExited (MouseEvent me) a
component
MouseMotionListener interface contains the following methods:
Method Description
This method is invoked when the mouse
public void mouseDragged (MouseEvent me) button
is pressed on a component and then dragged
public void mouseMoved (MouseEvent me) This method is invoked when the mouse cursor
has been moved onto a component but no
buttons have been pushed
The MouseEvent class has the following methods:
Method Description
int getButton () This method returns a value representing a mouse button, when it is
clicked it returns 1 if the left button is clicked, 2 if the middle button is
clicked and 3 if the right button is clicked
int getClickCount () This method returns the number of mouse clicks associated with this
event
int getX () This method returns the horizontal x position of the event relative to the
source component
114
int getY () This method returns the vertical y position of the event relative to the
source component
.
115
}
}
Output:
Handling Keyboard Events: A user interacts with the application by pressing keys on the
keyboard A programmer should know which key the user has pressed on the keyboard These
are also called „events‟ Knowing these events will enable the programmer to write his code
according to the key pressed KeyListener interface of javaawtevent package helps to know
which key is pressed or released by the user It has 3 methods:
Method Description
public void keyPressed (KeyEvent ke) This method is called when a key is pressed on the
keyboard This include any key on the keyboard along
with special keys like function keys, shift, alter, caps
lock, home and end etc
public void keyTyped (KeyEvent ke) This method is called when a key is typed on the
keyboard This is ame as keyPressed () method but
this method is called when general keys like A to Z or
1 to 9 etc are typed It cannot work with special keys
public void keyReleased (KeyEvent ke) This method is called when a key is released
KeyEvent class has the following methods to know which key is typed by the user:
Method Description
char getKeyChar () This method returns the key name (or character)
related to the key pressed or released
int getKeyCode () This method returns an integer number which is the
value of the key pressed by the user
The following are the key codes for the keys on the keyboard They are defined as constants in
KeyEvent class Remember VK represents Virtual Key
Key Code Description
VK_A to VK_Z To represent keys from a to z
VK_0 to VK_9 To represent keys from 0 to 9
VK_F1 to VK_F12 To represent keys from F1 to F12
116
. .
Program 15: Write a program to trap a key which is pressed on the keyboard
//Keyboard events
import javaawt*;
import javaawtevent*;
class KeyBoardEvents extends Frame implements KeyListener
{String str =" ";
KeyBoardEvents
()
{addKeyListener (this); addWindowListener (new
WindowAdapter ()
{public void windowClosing (WindowEvent we)
{Systemexit (0);
}
});
}
public void paint (Graphics g)
{gdrawString (str, 100, 100); str =
" ";
}
public void keyPressed (KeyEvent ke)
{int keyCode = kegetKeyCode(); if (
keyCode == KeyEventVK_F1)
str += "F1 key";
if ( keyCode == KeyEventVK_HOME)
str += "Home key";
repaint ();
}
public void keyReleased (KeyEvent ke)
{
}
public void keyTyped (KeyEvent ke)
{
}
public static void main (String args[])
{KeyBoardEvents ob = new KeyBoardEvents ();
obsetTitle ("Key demo");
obsetSize (600,450);
117
. .
obsetVisible (true);
}
}
Output:
Unit-V
Swings
When awt components are created, internally native methods (c language functions) are
executed which create peer component (equivalent component) awt components are heavy
weight components The look and feel of awt component change depending upon the operating
system
JFC represents a class library that is extended from awt JFC stands for Java Foundation
Classes JFC is an extension of the original awt, it does not replace awt JFC components are
light weight components, they take less system resources
Component JLabel
JTabbedPane
JTable
JCheckBox
(javaawt) JTextField
JTextComponent
JTextArea
JTableHeader JButton
AbstractButto
n JMenu
JMenuIte JRadioButtonMenuIte
m m
JCheckBoxMenuItem
<-------------------------- javaxswing------------------
---------------- ------------------- >
Creating a Frame:
Create an object to JFrame: JFrame ob = new JFrame ("title");
(or)
Create a class as subclass to JFrame class: MyFrame extends
JFrame
Create an object to that class : MyFrame ob = new MyFrame ();
. .
Output:
Note: To close the frame, we can take the help of getDefaultCloseOperation () method of
JFrame class, as shown here:
getDefaultCloseOperation
(constant); where the constant can be any one of
the following:
JFrameEXIT_ON_CLOSE: This closes the application upon clicking on close button
JFrameDISPOSE_ON_CLOSE: This disposes the present frame which is visible on the
screen The JVM may also terminate
JFrameDO_NOTHING_ON_CLOSE: This will not perform any operation upon clicking
on close button
JFrameHIDE_ON_CLOSE: This hides the frame upon clicking on close button
Window Panes: In swings the components are attached to the window panes onlyA window
pane represents a free area of a window where some text or components can be displayed For
example, we can create a frame using JFrame class in javaxswing which contains a free area
inside it, this free area is called 'window pane' Four types of window panes are available in
javaxswing package
120
.
Glass Pane: This is the first pane and is very close to the monitors screen Any
components to be displayed in the foreground are attached to this glass pane To reach this
glass pane, we use getGlassPane () method of JFrame class
Root Pane: This pane is below the glass pane Any components to be displayed in the
background are displayed in this pane Root pane and glass pane are used in animations
also For example, suppose we want to display a flying aeroplane in the sky The aeroplane
can be displayed as a gif or jpg file in the glass pane where as the blue sky can be
displayed in the root pane in the background To reach this root pane, we use getRootPane
() method of JFrame class
Layered Pane: This pane lies below the root pane When we want to take several
components as a group, we attach them in the layered pane We can reach this pane by
calling getLayeredPane () method of JFrame class
Content Pane: This is the bottom most pane of all Individual components are attached to
this pane To reach this pane, we can call getContentPane () method of JFrame class
Displaying Text in the Frame: paintComponent (Graphics g) method of JPanel class is used
to paint the portion of a component in swing We should override this method in our class In
the following example, we are writing our class MyPanel as a subclass to JPanel and override
the painComponent () method
Program 2: Wrire a program to display text in the frame
import javaxswing*;
import javaawt*;
class MyPanel extends JPanel
{public void paintComponent (Graphics g)
{superpaintComponent (g); //call JPanel‟s method
setBackground (Colorred);
gsetColor (Colorwhite);
gsetFont (new Font("Courier
New",FontBOLD,30)); gdrawString ("Hello
Readers!", 50, 100);
}
}
class FrameDemo extends JFrame
{FrameDemo ()
{
Container c = getContentPane
(); MyPanel mp = new
MyPanel (); cadd (mp);
setDefaultCloseOperation (JFrameEXIT_ON_CLOSE);
}
public static void main(String args[])
{FrameDemo ob = new FrameDemo ();
obsetSize (600, 200);
obsetVisible (true);
}
}
121
. .
Output:
JComponent Class Methods: JComponent class of javaxswing package is the subclass of the
Component class of javaawt So, whatever the methods are available in Component class are
also available to JComponent This is the reason why almost all the methods of AWT are
useful in swing also Additional methods found in JComponent are also applicable for the
components created in swing
When a component is created, to dislay it in the frame, we should not attach it to the frame
directly as we did in AWT On the other hand, the component should be attached to a window
pane
To add the component to the content pane, we can write, as:
cadd (component); where c represents the content pane which is represented
by Container object
Similarly, to remove the component we can use remove () method
as: cremove (component);
To remove all the components from the content pane we can use removeAll () method
as: cremoveAll ();
When components are to be displayed in the frame, we should first set a layout which
arranges the components in a particular manner in the frame as:
csetLayout (new FlowLayout ());
The following methods of JComponent class are very useful while handling the components:
To set some background color to the component, we can use setBackground () method,
as: componentsetBackground (Coloryellow);
To set the foreground color to the component, we can use setForeground () method,
as: componentsetForeground (Colorred);
To set some font for the text displayed on the component, we can use setFont () method
We should pass Font class object to this method, as:
componentsetFont (Font obj);
where, Font class object can be created as:
Font obj = new Font (“fontname”, style, size);
122
. .
PushButton:
· To create a JButton with text: JButton b = new JButton (“OK”);
· To create a JButton with image: JButton b = new JButton (ImageIcon ii);
· To create a JButton with text & image: JButton b = new JButton (“OK”, ImageIcon ii);
It is possible to create components in swing with images on it The image is specified by
ImageIcon class object
Program 3: Write a program to create a JButton component
//JButton Demo
import javaxswing*;
import javaawt*;
class JButton1 extends JFrame
{JButton b;
ImageIcon
ii; JButton1
()
{Container c = getContentPane ();
csetLayout (null);
ii = new ImageIcon("abcgif");
b = new JButton ("Click ME", ii);
bsetBounds(100,20,150,150);
bsetBackground (Coloryellow);
bsetForeground (Colorred);
cadd (b);
setDefaultCloseOperation (JFrameEXIT_ON_CLOSE);
}
public static void main(String args[])
{JButton1 ob = new JButton1 ();
123
. .
Label:
· To create a JLabel component: JLabel lbl = new JLabel ();
· To set text to JLabel component: lblsetText ("Hello");
JLabel lbl = new JLabel ("text",
· To create a JLabel with text: JLabelRIGHT);
· To create a JLabel with image: JLabel lbl = new JLabel (ImageIcon ii);
Program 4: Write a program to create a JLabel component
//JLabelDemo
import javaxswing*;
import javaawt*;
class JLabelDemo extends JFrame
{JLabel lbl;
ImageIcon ii;
JLabelDemo
()
{
Container c = getContentPane
(); csetLayout (null);
= new ImageIcon("abcgif");
lbl = new JLabel(ii);
lblsetBounds
(100,100,200,200); cadd (lbl);
setDefaultCloseOperation (JFrameEXIT_ON_CLOSE);
124
. .
}
public static void main(String args[])
{JLabelDemo ob = new JLabelDemo ();
obsetTitle ("Swing Frame example");
obsetSize (600,250);
obsetVisible (true);
}
}
Output:
Program 5: Write a program to create check boxes, radio buttons and text area components
//Check boxes and radio buttons
import javaxswing*;
import javaawt*;
import javaawtevent*;
125
. .
}
Output:
J2SEJ2EEMale
JComboBox class: JComboBox allows us to create a combo box, with a group of items
which are displayed as a drop down list The user can select a single item only
· To create an empty combo box: JComboBox box = new JComboBox ();
To create a combo box with array of elements:
JComboBox box = new JComboBox (Object
arr[]);
To create a combo box with vector of elements:
JComboBox box = new JComboBox (Vector v);
· To add the items to the combo box: boxaddItem (“ India”);
To retrieve the selected item from the combo Object obj = boxgetSelectedItem
· box: ();
· To retrieve the selected items index: int i = boxgetSelectedIndex ();
· To get the item of combo box by giving index: Object obj = boxgetItemAt (int index);
· To get number of items in the combo box: int n = boxgetItemCount ();
· To remove an item obj from the combo box: boxremoveItem (Object obj);
· To remove an item by giving index: boxremoveItemAt (int index);
· To remove all items: boxremoveAllItems ();
Program 6: Write a program to create a combo box with names of some countries
//JComboBox Demo
import javaawt*;
import javaxswing*;
import javaawtevent*;
class JComboBoxDemo extends JFrame implements ItemListener
{JComboBox box; JLabel
lbl;
JComboBoxDemo
()
{Container c = getContentPane();
csetLayout (null);
127
JList Class: JList class is useful to create a list which displays a list of items and allows the
user to select one or more items
128
. .
Program 7: Write a program to create a list box with names of some countries such that user
can
select one or more items
//JList Demo
import javaawt*;
import javaxswing*;
import javaxswingevent*;
class JListDemo extends JFrame implements ListSelectionListener
{JList lst; JLabel lbl;
Object arr [];
String
msg="";
JListDemo ()
{Container c = getContentPane();
csetLayout (null);
String items [ ] =
{"India","America","Germany","Japan","France"}; lst = new JList
(items);
lstsetBounds(100,20,100,100)
; cadd (lst);
lstaddListSelectionListener (this);
lbl = new JLabel ();
lblsetBounds (100, 150,200,40);
cadd(lbl);
setDefaultCloseOperation (JFrameEXIT_ON_CLOSE);
}
public void valueChanged (ListSelectionEvent le)
{arr= lstgetSelectedValues (); for (
int i=0;i<arrlength;i++)
msg += (String) arr [i];
lblsetText ("You Selected : " + msg);
msg = "";
}
public static void main(String args[])
{JListDemo ob = new JListDemo ();
obsetSize (500,250);
obsetTitle ("JListDemo");
obsetVisible (true);
}
. .
}
Output:
130
JTabbedPane: JTabbedPane is a container to add multiple components on every tab The user
can choose a component from a tab
· To create a JTabbedPane: JTabbedPane jtp = new JTabbedPane ();
· To add tabs: jtpaddTab ("title", object);
· To create a Panel containing some components: class MyPanel extends JPanel
Now pass 'MyPanel' class object to addTab ()
jtpremoveTabAt (int
· To remove a tab (and its components) from the tabbedpane: index);
· To remove all the tabs and their corresponding components: jtpremoveAll ();
Program 8: Write a program to create a tabbed pane with two tab sheets
//JTabbedPane demo
import javaawt*;
import javaxswing*;
class JTabbedPaneDemo extends JFrame
{JTabbedPaneDemo ()
{JTabbedPane jtp = new JTabbedPane (); jtpadd
("Countries", new CountriesPanel ());
jtpadd ("Capitals", new CapitalsPanel ());
Container c = getContentPane ();
cadd (jtp);
}
public static void main(String args[])
{JTabbedPaneDemo demo = new JTabbedPaneDemo ();
demosetSize (600,450);
demosetVisible (true);
demosetDefaultCloseOperation (JFrameEXIT_ON_CLOSE);
.
}
}
class CountriesPanel extends JPanel
{CountriesPanel ()
{JButton b1, b2, b3;
b1 = new JButton ("America");
b2 = new JButton ("India");
b3 = new JButton ("Japan");
add (b1); add (b2); add (b3);
}
}
class CapitalsPanel extends JPanel
{CapitalsPanel ()
{JCheckBox cb1 = new JCheckBox ("Washington");
JCheckBox cb2 = new JCheckBox ("New
Delhi"); JCheckBox cb3 = new JCheckBox
("Tokyo");
add (cb1); add (cb2); add (cb3);
131
}
}
Output:
JTable: JTable represents data in the form of a table The table can have rows of data, and
column headings
· To create a JTable: JTable tab = new JTable (data, column_names);
Here, data and column_names can be a 2D array or both can be vector of vectors
To create a row using a vector: Vector row = new Vector();
rowadd (object); //here object represents a
column rowadd (object);
rowadd (object);
To create a table heading, we use getTableHeader () method of JTable
class JTableHeader head = tabgetTableHeader ();
Note: JTableHeader class is defined in javaxswingtable package
Program 9:Write a program that creates a table with some rows and columns
//creating a table
import javaawt*;
import javaxswing*;
import javautil*;
import javaxswingtable*;
class JTableDemo extends JFrame
{JTableDemo ()
{Vector <Vector> data = new Vector <Vector> ();
//create first row
Vector <String> row = new Vector <String>
(); rowadd ("Ravi");
rowadd
("Manager");
rowadd ("50000");
dataadd (row);
132
JMenu Class: A menu represents a group of items or options for the uset to select To create a
menu, the following steps should be used:
133
FlowLayout: FlowLayout is useful to arrange the components in a line after the other When a
line is filled with components, they are automatically placed in the next line
Program 11: Write a program to create push buttons and arrange them using flow layout
//Flow layout example
import javaxswing*;
import javaawt*;
class Example1 extends JFrame
{Example1 ()
{Container c = getContentPane ();
csetLayout(new
FlowLayout(FlowLayoutLEFT,20,40)); // where 20 and
40 specifies hgap and vgap respectively JButton b1 =
new JButton ("First");
JButton b2 = new JButton
("Second"); JButton b3 = new
JButton ("Third"); //add(c);
cadd (b1); cadd (b2); cadd (b3);
setDefaultCloseOperation
(JFrameEXIT_ON_CLOSE);
}
public static void main(String args[])
{Example1 ob = new Example1 ();
obsetTitle ("Flow Layout");
obsetSize (600,250);
obsetVisible (true);
}
}
Output:
134
Program12: Write a program to create push buttons and arrange them using border layout
//Border layout example
import javaxswing*;
import javaawt*;
class Example2 extends JFrame
{Example2 ()
{Container c = getContentPane ();
csetLayout (new BorderLayout ());
JButton b1 = new JButton ("First");
JButton b2 = new JButton
("Second"); JButton b3 = new
JButton ("Third"); JButton b4 = new
JButton ("Fourth"); JButton b5 =
new JButton ("Fifth");
//add(c);
cadd (b1,"North"); cadd (b2,"South"); cadd (b3, "Center");
cadd (b4,"East"); cadd (b5,"West");
setDefaultCloseOperation (JFrameEXIT_ON_CLOSE);
}
public static void main(String args[])
{Example2 ob = new Example2 ();
obsetTitle ("Border Layout");
obsetSize (600,250);
obsetVisible (true);
}
}
Output:
135
CardLayout: A cardLayout is a layout managere which treats each component as a card Only
one card is visible at a time and the container acts as a stack of cards
Program 13: Write a program to create push buttons and arrange them using border layout
//Card layout example
import javaxswing*;
import javaawt*;
import javaawtevent*;
class Example3 extends JFrame implements ActionListener
{Container c;
CardLayout
card; Example3
()
{c = getContentPane ();
card = new CardLayout
(50,50); csetLayout (card);
JButton b1 = new JButton ("First");
JButton b2 = new JButton
("Second");
JButton b3 = new JButton ("Third");
cadd ("button1", b1);
cadd ("button2", b2);
cadd("button3", b3);
b1addActionListener (this);
b2addActionListener (this);
b3addActionListener (this);
setDefaultCloseOperation (JFrameEXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
cardnext(c); // when a button is clicked show the next card
}
public static void main(String args[])
{Example3 ob = new Example3 ();
obsetTitle ("Card Layout");
136
obsetSize (600,250);
obsetVisible (true);
}
}
Output:
GridLayout: It is useful to divide the container into a two dimensional grid form that contains
several rows and columns The container is divided into equal sized rectangles and one
component is placed in each rectangle GridLayout (), GridLayout (int rows, int cols),
GridLayout (int rows, int cols, int hgap, int vgap) are constructors
Program 14: Write a program to create push buttons and arrange them using grid layout
//Grid layout example
import javaxswing*;
import javaawt*;
class Example4 extends JFrame
{Container c;
GridLayout
grid; Example4
()
{c = getContentPane ();
grid = new GridLayout
(2,2,50,10); csetLayout (grid);
JButton b1 = new JButton ("First");
JButton b2 = new JButton
("Second"); JButton b3 = new
JButton ("Third"); cadd
("button1",b1);
137
cadd
("button2",b2);
cadd
("button3",b3);
setDefaultCloseOperation (JFrameEXIT_ON_CLOSE);
}
public static void main (String args[])
{Example4 ob = new Example4 ();
obsetTitle ("Grid Layout");
obsetSize (600,250);
obsetVisible (true);
}
}
. .
Output:
GridBagLayout: This layout is more flexible as compared to other layouts since in this
layout the components can span more than one row or column and the size of the components
can be adjusted to fit the display area
· To create grid bag layout: GridBagLayout obj = new GridBagLayout ();
To apply some constraints on the components, we should first create an object to
GridBagConstraints class, as: GridBagConstraints cons = new GridBagConstraints ();
GridBagConstraintsgridx, GridBagConstraintsgridy represents the row and column
positions of the component at upper left corner
GridBagConstraintsgridwidth, GridBagConstraintsgridheight specifies number of columns
and rows in the components display area
GridBagConstraintsipadx, GridBagConstraintsipady are useful to leave space horizontally
and vertically with in the component
138
Program 15: Write a program to create push buttons and arrange them using grid bag layout
//GridBag layout example
import javaxswing*;
import javaawt*;
class Example5 extends JFrame
{Container c; GridBagLayout
gbag;
GridBagConstraints
cons; Example5 ()
{c = getContentPane ();
gbag = new GridBagLayout
(); csetLayout (gbag);
cons = new GridBagConstraints(); JButton b1
= new JButton ("First"); JButton b2 = new
JButton ("Second"); JButton b3 = new
JButton ("Third"); JButton b4 = new JButton
("Fourth"); //for all buttons use horizontal
filling consfill =
GridBagConstraintsHORIZONTAL;
consgridx=0;
consgridy = 0;
gbagsetConstraints (b1,
cons); cadd (b1);
consgridx=1; consgridy =0;
gbagsetConstraints (b2,
cons); cadd (b2);
consgridx=2; consgridy = 0;
gbagsetConstraints (b3,
cons); cadd (b3);
consgridx=0;
consgridy = 1;
//add 100px height
wise consipady = 100;
139