0% found this document useful (0 votes)
11 views178 pages

Oop Unit 1 2 4 5

Uploaded by

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

Oop Unit 1 2 4 5

Uploaded by

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

U23ADT01​ OBJECT ORIENTED PROGRAMMING

Objectives:
•To understand Object Oriented Programming concepts and basics of Java programming language.​
•To learn the fundamentals core java, packages and collections for computing.​
•To provide a good knowledge on string handling.​
•To apply the various exception handling mechanism in java.​
• To design login id for Gmail using applet and AWT container in java program.

Course Outcomes:
Upon successful completion of this course, the students will be able to:
CO1: Understand the object-oriented programming principles using java.

CO2: Apply the types of Inheritance, Packages and Interfaces supported by Java

CO3: Understand and apply I/O file operations, Generics and String Handling.

CO4: Apply exception handling mechanisms and multithreaded model to solve real world problems

CO5: Develop AWT container and graphics applications in java.

UNIT-1 INTRODUCTION TO OOP AND JAVA ​ 9

Introduction to object-oriented languages : Object oriented programming paradigm -Basic concepts


of object-oriented programming - Procedural vs Object oriented programming.-An overview of Java-
Data Types, Variables, and Arrays - Operators-Control Statements – Classes – Methods – access
specifies –staticmembers – Constructor- Destructor.

UNIT-II INHERITANCE, INTERFACES AND PACKAGES​ ​ 9

Inheritance – Inheritance hierarchies super and sub classes, Member access rules, super keyword,
preventing inheritance: final classes and methods, the Object class and its methods.
Interfaces- Interfaces Vs Abstract classes, defining an interface, implement interfaces, Inner classes-
Uses of inner classes, local inner classes, anonymous inner classes, static inner classes, examples.
Packages- Defining, creating and accessing a package, Understanding CLASSPATH, importing
packages.

UNIT-III I/O AND STRING HANDLING IN JAVA​ ​ ​ ​ ​ 9

I/O Basics – Reading and Writing Console I/O – Reading and Writing Files. Generics: Generic
Programming – Generic classes – Generic Methods – Bounded Types. Strings: Basic String class,
methods and String Buffer Class.​ ​ ​ ​

UNIT-IV EXCEPTION HANDLING AND THREADS​ ​ ​ ​ ​ ​ 9


Exception Handling: Fundamentals of Exception handling and types - Built in Exceptions - User
defined Exceptions.- Multithreaded Programming : Thread Model - The Main Thread - Creating a
Thread - Creating Multiple Threads – Thread priorities - Synchronization - Inter thread
communication. wrappers-Auto boxing.

UNIT-V GUI PROGRAMMING AND SWING ​ ​ ​ ​ ​ ​ 9

Introduction, limitations of AWT- MVC architecture- components- containers. Understanding Layout


Managers- Flow Layout- Border Layout- Grid Layout- Card Layout- Grid Bag Layout. Event
Handling- The Delegation event model- Events- Event sources- Event Listeners- Event classes A
Simple Swing Application- Applets – Applets and HTML- Security Issues- Applets and
Applications- passing parameters to applets. Creating a Swing Applet- Painting in Swing- A Paint
example- Exploring Swing Controls- JLabel and Image Icon, JText Field, The Swing Buttons-
JButton- JToggle Button- JCheck Box- JRadio Button- JTabbed Pane- JScroll Pane- JList- JCombo
Box- Swing Menus, Dialogs.

Total period:45

Text books:

S. No Author(s) Title of Book Publisher Year of


publication
1 Paul Dietel and Java how to Pearson 2016
Harvey program Education
2 Larry L Peterson Computer network Morgan 2011
Bruce Kauffman
3 Robert Sebesta Programming the Addison 2015
world wide web Wesley
4 Herbert schildt The complete Tata McGraw 2014
reference Hill
References:

S. No Author(s) Title of Book Publisher Year of


publication
1 Joyce Farrell Java Cengage 2014
programming Learning
2 Herbert Schildt and Dale Java Tata McGraw 2017
Skrien Fundamentals Hill

2
UNIT-1 INTRODUCTION TO OOP AND JAVA

OBJECT-ORIENTED PROGRAMMING
Object-Oriented Programming (OOP) is a programming language model
organized around objects rather than actions and data. An object-oriented program can be
characterized as data controlling access to code. Concepts of OOPS
●​ Object
●​ Class
●​ Inheritance
●​ Polymorphism
●​ Abstraction
●​ Encapsulation
OBJECT
Object means a real word entity such as pen, chair, table etc. Any entity that has state
and behavior is known as an object. Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory. Objects can communicate without
knowing details of each other's data or code, the only necessary thing is that the type of
message accepted and type of response returned by the objects.
An object has three characteristics:
●​ state: represents data (value) of an object.
●​ behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
●​ identity: Object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. But, it is used internally by the JVM to
identify each object uniquely.
CLASS
Collection of objects is called class. It is a logical entity. A class can also be defined as
a blueprint from which you can create an individual object. A class consists of Data members
and methods.The primary purpose of a class is to hold data/information. The member functions
determine the behavior of the class,
i.​ e. provide a definition for supporting various operations on data held in the form of
an object.Class doesn’t store any space.
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the
properties and behavior of one class to another, i.e., acquiring the properties and behavior of
child class from the parent class. When one object acquires all the properties and behaviours of
another object, it is known as inheritance. It provides code reusability and establishes
relationships between different classes. A class which inherits the properties is known as Child
Class(sub-class or derived class) whereas a class whose properties are inherited is known as
Parent class(super-class or base class). Types of inheritance in java: single, multilevel and
hierarchical inheritance. Multiple and hybrid inheritance is supported through interface only.

3
POLYMORPHISM
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or rectangle etc.

POLYMORPHISM IS CLASSIFIED INTO TWO WAYS:


Method Overloading(Compile time Polymorphism)

Method Overloading is a feature that allows a class to have two or more methods having the
same name but the arguments passed to the methods are different. Compile time
polymorphism refers to a process in which a call to an overloaded method is resolved at
compile time rather than at run time.
METHOD OVERRIDING(RUN TIME POLYMORPHISM)
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.In other words, If subclass provides the specific implementation of
the method that has been provided by one of its parent class, it is known as method overriding.

ABSTRACTION
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. For example: phone call, we don't know the internal processing.In
java, we use abstract class and interface to achieve abstraction.
ENCAPSULATION
Encapsulation in java is a process of wrapping code and data together into a single
unit, for example capsule i.e. mixed of several medicines.A java class is the example of
encapsulation.

4
Overview of OOP

OBJECT ORIENTED PROGRAMMING (OOP):

Object-Oriented Programming System (OOPs) is a programming paradigm based onthe concept of


―objects that contain data and methods, instead of just functions and procedures.

✔​ The primary purpose of object-oriented programming is to increase the flexibility


and maintainability of programs.
✔​ Object oriented programming brings together data and its behavior (methods) into
a single entity (object) which makes it easier to understand how a program works.

●​ FEATURES / ADVANTAGES OF OBJECT ORIENTED PROGRAMMING :-


1.​ It emphasis in own data rather than procedure.
2.​ It is based on the principles of inheritance, polymorphism, encapsulation
and dataabstraction.
3.​ Programs are divided into objects.
4.​ Data and the functions are wrapped into a single unit called class so that
data ishidden and is safe from accidental alternation.
5.​ Objects communicate with each other through functions.
6.​ New data and functions can be easily added whenever necessary.
7.​ Employs bottom-up approach in program design.

​ PROCEDURE-ORIENTED PROGRAMMING [POP]:


Procedure-Oriented Programming is a conventional programming which
consists of writing a list of instructions for the computer to follow and
organizing these instructions into groups known as Functions (or)
Procedures (or) subroutines (or)Modules.
Example: A program may involve the following operations:
✔​ Collecting data from user (Reading)
✔​ Calculations on collected data (Calculation)
✔​ Displaying the result to the user (Printing)

5
CHARACTERISTICS OF PROCEDURAL ORIENTED PROGRAMMING:-
1.​ It focuses on process rather than data.
2.​ It takes a problem as a sequence of things to be done such as
reading, calculating and printing. Hence, a number of functions are
written to solve a problem.
3.​ A program is divided into a number of functions and each function
has clearly defined purpose.
4.​ Most of the functions share global data.
5.​ Data moves openly around the system from function to function.
6.​ Employs top-down approach in program design.

DRAWBACK OF POP
⮚​ Procedural languages are difficult to relate with the real world objects.
⮚​ Procedural codes are very difficult to maintain, if the code grows larger.
⮚​ Procedural languages do not have automatic memory management as like in
Java. Hence, it makes the programmer to concern more about the memory
management of the program.
The data, which is used in procedural languages, are exposed to the whole
program.So, there is no security for the data.
⮚​ Examples of Procedural languages :
o​ BASIC
o​ C
o​ Pascal
o​ FORTRAN
​ Difference between POP and OOP:
Procedure Oriented
Object Oriented Programming
Programming
Divided Into In POP, program is divided into In OOP, program is divided into
smallparts called functions. partscalled objects.

6
In POP, Importance is not given to In OOP, Importance is given to the
Importance data but to functions as well data rather than procedures or
JAVA – as sequence of actions to be done. functions because it works as a
DATA real world.
TYPES Approach POP​ follows​ Top​ Down OOP​ follows​ Bottom​ Up
approach. approach.
Access POP does not have any OOP has​ access​ specifiers
Specifiers accessspecifier. named​ Public,​
Private,
Protected, etc.
In POP, Data can move freely from In OOP, objects can move and
Data Moving function to function in the system. communicate with each other
throughmember functions.
Expansion To add new data and function in OOP provides an easy way to add
POPis not so easy. newdata and function.
In POP, Most function uses Global In OOP, data cannot move easily
Data Access data for sharing that can be from function to function, it can be
accessed freely from function to kept public or private so we can
function in the control the access of data.
system.
Data Hiding POP​ does​ not​ have​ OOP​ provides​ Data​ Hiding​
any proper wayfor hiding data so it so provides more security.
is less secure.
In​ POP,​ Overloading​ is​ In OOP, overloading is possible in
Overloading not possible. the form of Function Overloading
and Operator Overloading.
Examples Examples of​ POP​ are: C,VB, Examples of OOP are: C++, JAVA,
FORTRAN, and Pascal. VB.NET, C#.NET.
DATA TYPE IS USED TO ALLOCATE SUFFICIENT MEMORY SPACE FOR THE DATA. DATA TYPES
SPECIFY THE DIFFERENT SIZES AND VALUES THAT CAN BE STORED IN THE VARIABLE.

⮚​ JAVA IS A STRONGLY TYPED LANGUAGE.


​ Definition: strongly Typed Language:
Java is a strongly typed programming language because every variable must be
declared with a data type. A variable cannot start off life without knowing the range
of values it can hold, and once it is declared, the data type of the variable cannot
change.
Data types in Java are of two types:

1.​ Primitive data types (Intrinsic or built-in types ) :- : The primitive data
types include boolean, char, byte, short, int, long, float and double.
2.​ Non-primitive data types (Derived or Reference Types): The
non-primitive data types include Classes, Interfaces, Strings and Arrays.

7
1.​ PRIMITIVE TYPES:
Primitive data types are those whose variables allow us to store only one
value and neverallow storing multiple values of same type. This is a data type
whose variable can hold maximum one value at a time.

There are eight primitive types in Java:


INTEGER TYPES:
1.​int
2.​short
3.​lomg
4.​byte
FLOATING-POINT TYPES:
5.​float
6.​double
OTHERS:
7.​char
8.​Boolean

⮚​ INTEGER TYPES:
The integer types are form numbers without fractional parts. Negative values
are allowed.Java provides the four integer types shown below:

Storage Default
Type Range Example
Requirement Value
-2,147,483,648(-2^31)
int a = 100000,
int 4 bytes to 0
int b = -200000
2,147,483,647
(2^31-1)
short s = 10000,
short 2 bytes -32,768 (-2^15) to 32,767 (2^15-1) 0
short r = -20000
-9,223,372,036,854,775,808 (-2^63)
long a =
long 8 bytes to 0L
100000L, int b =
9,223,372,036,854,775,808 (2^63-1)
-200000L
byte a = 100 ,
byte 1 byte -128 (-2^7) to 127 (2^7-1) 0
byte b = -50
⮚​ FLOATING-POINT TYPES:
The floating-point types denote numbers with fractional parts.
The two floating-pointtypes are shown below:

Storage Defa
Type Range Example
Requirement t

8
Valu
Approximately​
Float 4 bytes float f1 =234.5f 0.0f
±3.40282347E+38F (6-7
significant decimal digits)
Approximately
double​ d1​
double 8 bytes ±1.79769313486231570E+308 0.0d
= 123.4
(15 significant decimal digits)
⮚​ CHAR:

●​ C
Char
●​ Char data type is a single 16-bit Unicode character.
●​ Minimum value is '\u0000' (or 0).
●​ Maximum value is '\uffff' (or 65,535 inclusive).
●​ Char data type is used to store any character.
●​ Example: char letterA ='A'

⮚​ BOOLEAN:

●​ boolean data type represents one bit of information.


●​ There are only two possible values: true and false.
●​ This data type is used for simple flags that track true/false conditions.
●​ Default value is false.
●​ Example: boolean one = true

2.​ DERIVED TYPES (REFERENCE TYPES):


●​ Derived data types are those whose variables allow us to store multiple
values of same type. But they never allow storing multiple values of
different types.
●​ A reference variable can be used to refer to any object of the declared type or any
compatible type.
●​ These are the data type whose variable can hold more than one value of
similar type.
●​ THE VALUE OF A REFERENCE TYPE VARIABLE, IN CONTRAST TO THAT OF A PRIMITIVE TYPE, IS A
REFERENCE TO (AN ADDRESS OF) THE VALUE OR SET OF VALUES REPRESENTED BY THE VARIABLE.

●​ Example
int a[] = {10,20,30};


// valid int b[] = {100, 'A',
"ABC"};

// invalid

9
Animal animal = new Animal("giraffe"); //Object

JAVA - VARIABLES

⮚​ A VARIABLE IS A NAMED PIECE OF MEMORY THAT IS USED FOR STORING DATA IN JAVA
PROGRAM.
⮚​ A variable is an identifier used for storing a data value.
⮚​ A Variable may take different values at different times during the
execution if the program, unlike the constants.
⮚​ The​ variable's type​ determines what​ values it​ can​
hold​ and what operations can beperformed on it.
⮚​ SYNTAX TO DECLARE VARIABLES:
datatype identifier [=value][,identifier [ =value] …];

⮚​ Example of Variable names:


int average=0.0, height, total height;

⮚​ RULES​ FOLLOWED​ FOR​ VARIABLE​ NAMES​ (​ CONSIST​ OF​


ALPHABETS,​ DIGITS, UNDERSCORE ANDDOLLAR CHARACTERS)

1.​ A variable name must begin with a letter and must be a sequence of letter
or digits.
2.​ They must not begin with digits.
3.​ Uppercase and lowercase variables are not the same.
a.​ Example: Total and total are two variables which are distinct.
4.​ It should not be a keyword.
5.​ Whitespace is not allowed.
6.​ Variable names can be of any length.

⮚​ INITIALIZING VARIABLES:
✔​ After the declaration of a variable, it must be initialized by means of
assignment statement.
✔​ It is not possible to use the values of uninitialized variables.

✔​ Two ways to initialize a variable:


1.​ Initialize after declaration:
SYNTAX:
​ ​ ​ ​ ​ ​ ​ ​ ​
int months;
months=1;

10
2.​Declare and initialize on the same line:

SYNTAX:

int months=12;
⮚​ DYNAMIC INITIALIZATION OF A VARIABLE:
Java allows variables to be initialized dynamically using any valid expression at the
timethe variable is declared.

EXAMPLE: PROGRAM THAT COMPUTES THE REMAINDER OF THE DIVISION OPERATION:

class FindRemainer
{

public static void main(String arg[]) {int num=5,den=2;


int rem=num%den; System.out.println(―Remainder is ―+rem);
}

OUTPUT:
Remainder is 1

In the above program there are three variables num, den and rem. num and
den ate initialized by constants whereas rem is initialized dynamically by the
modulo division operation on num and den.

There are three kinds of variables in Java:


1.​ Local variables
2.​ Instance variables
3.​ Class/static variables

Local Variables Instance Variable Class / Static Variables

11
Class variables also known as
EXAMPLE static variables are declared
PROGRAM Instance variables are declared with the static keyword in a
in a class, but outside a​ class, but outside a method,
Local variables aredeclared in constructor or a block.
method, constructor or any
methods, constructors, or There would only be one copy
block.
blocks. of each class variable per clas
regardless of how many objec
are created from it.

Local variables are created


when the method, constructor Instance variables are created
Static variables are created wh
or block is entered and the when an object is created with
the program starts and destroy
variable will be destroyed once the use of the keyword 'new'
when the program stops.
it exits the method, constructor and destroyed when the object
or block. is destroyed.

Access modifiers cannot be used Access modifiers can be used Access modifiers can be used
for local variables. forinstance variables. for class variables.

Local variables are visible only The instance variables are Visibility is similar to instance
within the declared method, visible​ for​ all​ methods, variables.
constructor or block. constructors and block in the
class.
Instance variables have default
values. For numbers the default
There is no default value for value is 0, for Booleans it is
local variables so local false and for object references it Default values are same as
variables should be declared is null. Values can be assigned instance variables.
and an initial value shouldbe during
assigned before the first use. the declaration or within the
constructor.
Instance variables can be
accesseddirectly by calling the
variable name inside the class.
However within static methods Static variables can be accesse
Local variables can only be
and different class should be by calling with the class name
access inside the declared
block. called using the fully qualified ClassName.VariableName.
name as follows:
ObjectReference.VariableNa
me.
ILLUSTRATING THE USE OF ALL THE ABOVE VARIABLES:

​ class area
{
int length=20; int breadth=30;

static int classvar=2500; void calc()

12
{
int areas=length*breadth;
System.out.println(“The area is “+areas+” sq.cms”);
}

public static void main(String args[])


{
area a=new area(); a.calc();
System.out.println(“Static Variable Value : “+classvar);
}
}

OUTPUT:
The area is 600 sq.cms
Static Variable Value :
2500
PROGRAM EXPLANATION:
Class name: area
Method names: calc() and main()
Local variables: areas (accessed only in the particular method)
Instance variables: length and breadth (accessed only through the object‘s method) Static
variable: accessed anywhere in the program, without object reference

ARRAYS
AN ARRAY IS A COLLECTION OF SIMILAR TYPE OF ELEMENTS WHICH HAS CONTIGUOUS MEMORY LOCATION.
Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed set of
elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.

ADVANTAGE OF ARRAY:
•​ Code Optimization: It makes the code optimized; we can retrieve or sort the
data easily.
•​ Random access: We can get any data located at any index position.

13
DISADVANTAGE OF ARRAY:
●​ Size Limit: We can store only fixed size of elements in the array. It doesn't
growits size at runtime.

TYPES OF ARRAY:
There are two types of array.
1.​ One-Dimensional Arrays
2.​ Multidimensional Arrays

1.​ONE-DIMENSIONAL ARRAY:

⮚​ Creating an array:
Three steps to create an array:
1.​Declaration of the array
2.​Instantiation of the array
3.​Initialization of arrays
1.​DECLARATION OF THE ARRAY:
Declaration of array means the specification of array variable, data_type and array_name.
SYNTAX TO DECLARE AN ARRAY IN JAVA:

Example:

int[] floppy; (or) int []floppy (or) int floppy[];


2.​Instantiation of the array:

SYNTAX:
arrayRefVar=new datatype[size];

Example:​ floppy=new int[10];

3.​ Initialization of arrays:Definition:

14
Syntax to initialize values to array element:

Example:
floppy[0]=20;

SHORTHAND TO CREATE AN ARRAY OBJECT:


Java has shorthand to create an array object and supply initial values at the same time when it
is created.

EXAMPLE 1:
int regno[]={101,102,103,104,105,106};
int reg[]=regno;

Example 2: double[] myList = new double[10];

ARRAY LENGTH:
The variable length can identify the length of array in Java. To find the number of
elements of an array, use array.length.
EXAMPLE1:
int regno[10]; len1=regno.length;
EXAMPLE 2:
for(int
i=0;i<reno.len
gth;i++)
System.out.pr
intln(regno[i])
;

Following picture represents array myList. Here, myList holds ten double values
and the indicesare from 0 to 9.
Example: (One-Dimensional Array)

15
class Array
{

public static void main(String[] args)


{

int month_days[];
month_days=new int[12];
month_days[0]=31;
month_days[1]=28;
month_days[2]=31;
month_days[3]=30;
month_days[4]=31;
month_days[5]=30;
month_days[6]=31;
month_days[7]=31;
month_days[8]=30;
month_days[9]=31;
month_days[10]=30;
month_days[11]=31;

System.out.println(“April has ”+month_days[3]+ “ days.”);


}

OUTPUT:

April has 30 days.

Example 2: Finding sum of the array elements and maximum from the array:

16
public class TestArray{
public static void main(String[] args)
{

double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements

for (double element: myList)


{

System.out.println(element);
}

// Summing all elementsdouble total = 0;

for (int i = 0; i < myList.length; i++)


{

total += myList[i];
}

System.out.println("Total is " + total);

// Finding the largest elementdouble

max = myList[0];
for (int i = 1; i < myList.length; i++)
{

if (myList[i] > max)


max = myList[i];
}

System.out.println("Max is " + max);


}}

OUTPUT:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
2.​Multidimensional Arrays:
Definition:

17
Uses of Multidimensional Arrays:

✔​ Used for table


✔​ Used for more complex arrangements
SYNTAX TO DECLARE MULTIDIMENSIONAL ARRAY IN JAVA:

Example to instantiate Multidimensional Array in java:

int[][] arr=new int[3][3]; //3 row and 3 column - internally this matrix is implemented as
arrays of arrays of int.

EXAMPLE TO INITIALIZE MULTIDIMENSIONAL ARRAY IN JAVA:


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
EXAMPLES TO DECLARE, INSTANTIATE, INITIALIZE AND PRINT THE 2DIMENSIONAL ARRAY:
class twoDarray
{

public static void main(String args[])


{

int array1[][]=new int[4][5];// declares an 2D array.

int array2[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing 2D arrayint i,j,k=0;

// Storing and printing the values of Array1

System.out.println("-------Array 1​ " );
for(i=0;i<4;i++)
{

for(j=0;j<5;j++)

18
{

array1[i][j]=k;k++;
System.out.print(array1[i][j]+"");
}

System.out.println();
}// printing 2D array2

System.out.println("-------Array 2​ ");
for(int i=0;i<3;i++)
{

for(int j=0;j<3;j++)
{System.out.print(array2[i][j]+

System.out.println();
}

}}

Output:

-------------Array1------
------ 0 1 2 3 4

56789

10 11 12 13 14

15 16 17 18 19

-------------Array2------------

123

245

445

In the above program, the statement​ int array1[][]=new int[4][5]; is


interpreted automatically as follows:

array1[0]=new int[5];array1[1]=new int[5];array1[2]=new int[5];array1[3]=new int[5];


It means that, when we allocate memory for a multidimensional array, we need to only
specify the memory for the first (leftmost) dimension. We can allocate the remaining
dimensions separately with different sizes.

19
EXAMPLE: MANUALLY ALLOCATE DIFFERING SIZE SECOND DIMENSIONS:
class twoDarray
{

public static void main(String args[])


{

int array1[][]=new int[4][];​ // declares an 2D array.

array1[0]=new int[1];

array1[1]=new int[2];

array1[2]=new int[3];

array1[3]=new int[4];

int i,j,k=0;

// Storing and printing the values of Array

for(i=0;i<4;i++)
{ for(j=0;j<i+1;j++) {

array1[i][j]=k;k++;
System.out.print(array1[i][j]+ " ");
}

System.out.println();
}}

OUTPUT:
0
12
345
678
OPERATORS
Operators are used to manipulate primitive data types.
Java operators can be classified as unary,binary, or ternary—meaning taking one, two, or three
arguments, respectively.
Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform
various operations
i.e.:

20
o​ incrementing/decrementing a value by one
o​ negating an expression
o​ inverting the value of a boolean
JAVA UNARY OPERATOR EXAMPLE: ++ AND –
1.​ class OperatorExample
2.​ {
3.​ public static void main(String args[])
4.​ {
5.​ int x=10;
6. System.out.println(x++); //10 (11)
7. System.out.println(++x); //12
8. System.out.println(x--); //12 (11)
9. System.out.println(--x); //108.
10.}
11.}
Output:

10
12
12
10

JAVA UNARY OPERATOR EXAMPLE 2: ++ AND –


1.​ class OperatorExample
2.​ {
3.​ public static void main(String args[])
4.​ {
5.​ int a=10;
6.​ int b=10;
7.​ System.out.println(a++ + ++a);​ //10+12=22
8.​ System.out.println(b++ + b++);​ //10+11=21 7.
9.​ }
10.​}
OUTPUT:
22
21

Java Unary Operator Example: ~ and !

1.​ class OperatorExample{


2.​ public static void main(String args[]){
3.​ int a=10;

21
4.​ int b=-10;
5.​ BOOLEAN C=TRUE;

6.​ boolean d=false;


7.​ System.out.println(~a);​ //-11 (minus of total positive value which starts
from 0)
8.​ System.out.println(~b);​ //9 (positive of total minus, positive starts
from 0)
9.​ System.out.println(!c);​ //false (opposite of boolean value)
10.​ System.out.println(!d);​ //true
11.​ }
12.​ }

OUTPUT:
-11
9
False true
A binary or ternary operator appears between its arguments.Java operators
eight different categories:
1.​ Assignment
2.​ Arithmetic
3.​ Relational
4.​ Logical
5.​ Bitwise
6.​ Compound assignment
7.​ Conditional
8.​ Type.
Assignment Operators =
Arithmetic Operators -​ + * / % ++ --
Relational Operators > < >=​ <=​ == !=
Logical Operators &&​ ||​ & | ! ^
Bit wise Operator & | ^ >> >>>
Compound Assignment +=​ -=​ *=​ /= %=
Operators <<= >>= >>>=
Conditional Operator ?:

Java Assignment Operator


The java assignment operator statement has the following syntax:
<variable> = <expression>

If the value already exists in the variable it is overwritten by the assignment operator (=).

22
JAVA ASSIGNMENT OPERATOR EXAMPLE
1.​ class OperatorExample{
2.​ public static void main(String args[])
3.​ {
4.​ int a=10;
5.​ int b=20;
6.​ a+=4;​ //a=a+4 (a=10+4)
7.​ b-=4;​ //b=b-4 (b=20-4)
8.​ System.out.println(a);
9.​ System.out.println(b);
10.​ }
11.​}
OUTPUT:

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division.They act as basic mathematical operations.

Assume integer variable A holds 10 and variable B holds 20, then:

JAVA Operator Description Example


A + B will give
+ Addition - Adds values on either side of the operator
30
Subtraction - Subtracts right hand operand from left hand operand A - B will give
-
-10
A * B will give
* Multiplication - Multiplies values on either side of the operator
200
/ Division - Divides left hand operand by right hand operand B / A will give 2
Modulus - Divides left hand operand by right hand operand B % A will give
%
and returns remainder 0
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19
ARITHMETIC OPERATOR EXAMPLE: EXPRESSION
1.​ class OperatorExample
2.​ {
3.​ public static void main(String args[])
4.​ {

23
5.​ System.out.println(10*10/5+3-1*4/2);4.
6.​ }
7.​ }

OUTPUT:
​ 21​

RELATIONAL OPERATORS
Relational operators in Java are used to compare 2 or more objects. Java provides sixrelational
operators: Assume variable A holds 10 and variable B holds 20, then:

Operator Description Example


Checks if the values of two operands are equal or not, if yes (A == B) is not
==
then condition becomes true. true.
Checks if the values of two operands are equal or not, ifvalues
!= (A != B) is true.
are not equal then condition becomes true.
Checks if the value of left operand is greater than the value of (A > B) is not
>
right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value
< (A < B) is true.
ofright operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal (A >= B) is not
>= tothe value of right operand, if yes then condition becomes true.
true.

Checks if the value of left operand is less than or equal to the


<= value of right operand, if yes then condition becomestrue. (A <= B) is true.

LOGICAL OPERATORS
Logical operators return a true or false value based on the state of the Variables. Given that x
and y represent boolean expressions, the boolean logical operators are defined in the Table
below.

x&y x|y
X y !x x && y x || y x^y
True true false true true False
True false false false true true
False true true false true true
False false true false false false

24
BITWISE OPERATORS
Java provides Bit wise operators to manipulate the contents of variables at the bit level. The
result of applying bitwise operators between two corresponding bits in the operandsis shown
in the Table below.
A B ~A A&B A|B A^B

1 1 0 1 1 0

1 0 0 0 1 1

0 1 1 0 1 1

0 0 1 0 0 0

COMPOUND ASSIGNMENT OPERATORS


The compound operators perform shortcuts in common programming operations. Javahas
eleven compound assignment operators.
Syntax:​ argument1 operator = argument2.

JAVA ASSIGNMENT OPERATOR EXAMPLE


1.​ class OperatorExample
2.​ {
3.​ public static void main(String[] args)
4.​ {
5.​ int a=10;
6.​ a+=3;​ //10+3
7.​ System.out.println(a);
8.​ a-=4;​ //13-4
9.​ System.out.println(a);
10.​a*=2;​ //9*2
11.​System.out.println(a);
12.​a/=2;​ //18/2
13.​System.out.println(a);12.
14.​}
15.​}
OUTPUT:
13​
9
18
9

CONDITIONAL OPERATORS
The Conditional operator is the only ternary (operator takes three arguments) operator in

25
Java. The operator evaluates the first argument and, if true, evaluates the second argument.
If the first argument evaluates to false, then the third argument is evaluated. The conditional
operator is the expression equivalent of the if-else statement.
The conditional expression can be nested and the conditional operator associates from right
to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c?d:e):f):g)

EXAMPLE:

instanceof Operator:
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type(class type or interface type). instanceof operator is written as:
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true. Following is the
EXAMPLE:
public class Test
{

public static void main(String args[])


{String name = "James";

// following will return true since name is type of String

boolean result = name


instanceof String;
System.out.println( result );

26
}}

THIS WOULD PRODUCE THE FOLLOWING RESULT:


True

OPERATOR PRECEDENCE:
The order in which operators are applied is known as precedence. Operators with a higher
precedence are applied before operators with a lower precedence.
The operator precedence order of Java is shown below. Operators at the top of the table are
applied before operators lower down in the table.
If two operators have the same precedence, they are applied in the order they appear in a
statement. That is, from left to right. You can use parentheses to override the default
precedence.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

EXAMPLE:

In an operation such as,


RESULT =4+5*3

First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note
that ‗*‘ takes higher precedence than ‗+‘ according to chart shown above. This kindof
precedence of one operator over another applies to all the operators.
CONTROL-FLOW STATEMENTS

27
Java Control statements control the order of execution in a java program, based on data
values and conditional logic.

There are three main categories of control flow statements;


·​ Selection statements: if, if-else and switch.
·​ Loop statements: while, do-while and for.
·​ Transfer statements: break, continue, return, try-catch-finally and assert.
We use control statements when we want to change the default sequential order of execution

There are two types of decision making statements in Java. They are:
●​ if statements
●​ if-else statements
●​ nested if statements
●​ if-else if-else statements
●​ switch statements

if Statement:
●​ An if statement consists of a Boolean expression followed by one or more
statements.

●​ Block of statement is executed when the condition is true otherwise no statement


will be executed.Syntax:

●​ SYNTAX
IF(<CONDITIONAL EXPRESSION>)

{< Statement Action>

If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed.

If not the first set of code after the end of the if statement (after the closingcurly brace) will
be executed.
FLOWCHART:

28
if-else Statement:
The if/else statement is an extension of the if statement. If the statements in the
ifstatement fails, the statements in the else block are executed.
SYNTAX:
The if-else statement has the following syntax:

IF(<CONDITIONAL EXPRESSION>)

< Statement Action1>

else

< Statement Action2>

29
NESTED IF STATEMENT:
Nested if-else statements, is that using one if or else if statement inside another if or
else ifstatement(s).
SYNTAX:

if(condition1)
{

if(condition2)
{

//Executes this block if condition is True


}

else
{

//Executes this block if condition is false


}

else
{

//Executes this block if condition is false


}

30
IF...ELSE IF...ELSE STATEMENT:
An if statement can be followed by an optional else if...else statement, which is veryuseful to test
various conditions using single if...else if statement.
Syntax:

if(Boolean_expression 1){

//Executes when the Boolean expression 1 is true

}else if(Boolean_expression 2){

//Executes when the Boolean expression 2 is true

}else if(Boolean_expression 3){

//Executes when the Boolean expression 3 is true

}else {

//Executes when the none of the above condition is true.

EXAMPLE:
public class Test {

public static void main(String args[]){

31
OUTPUT:
Value of X is 30

switch Statement:

●​ THE SWITCH CASE STATEMENT, ALSO CALLED A CASE STATEMENT IS A MULTI-WAY


BRANCH WITH SEVERAL CHOICES. A SWITCH IS EASIER TO IMPLEMENT THAN A SERIES OF
IF/ELSE STATEMENTS.
A switch statement allows a variable to be tested for equality against a list of

Values. Eachvalue is called a case, and the variable being switched on is checked for
each case.
The switch statement begins with a keyword, followed by an expression that equates
to a no long integral value. Following the controlling expression is a code block that
contains zero or more labeled cases. Each label must equate to an integer constant and
each must be unique.
When the switch statement executes, it compares the value of the controlling
expression to the values of each case label.
The program will select the value of the case label that equals the value of the
controllingexpression and branch down that path to the end of the code block.
If none of the case label values match, then none of the codes within the
switch statementcode block will be executed.
Java includes a default label to use in cases where there are no matches. We
can have a nested switch within a case block of an outer switch.
EXAMPLE:
public class SwitchCaseStatementDemo {

public static void main(String[] args) {int a


=10, b = 20, c = 30;
int status = -1;
if (a > b && a > c) {
status = 1;
} else if (b > c) {
status = 2;
} else {
status = 3;
}

switch (status) {case 1:


System.out.println("a is the greatest");
break;
case 2:

case 3: default:

System.out.println("b is the greatest");break;


System.out.println("c is the greatest");break;

System.out.println("Cannot be determined");

OUTPUT:
c is the greatest

While Statement

●​ The while statement is a looping control statement that executes a


blockof code while a condition is true. It is entry controlled loop.
●​ You can either have a single statement or a block of code within the
while loop.The loop will never be executed if the testing expression
evaluates to false.
●​ The loop condition must be a boolean expression.
SYNTAX:
The syntax of the while loop is
while (<loop condition>)

<statements>

Example:

public class WhileLoopDemo {


public static void main(String[] args)
{int count = 1;
System.out.println("Printing Numbers from 1 to 10");
while (count <= 10) {
System.out.println(count++);
}

OUTPUT
Printing Numbers from 1 to 10
1
2
3​
4
5
6
7
8
9
10

DO-WHILE LOOP STATEMENT


do while loop checks the condition after executing the statements atleast once.
Therefore it is called as Exit Controlled Loop.
The do-while loop is similar to the while loop, except that the test is
performed at the endof the loop instead of at the beginning.
This ensures that the loop will be executed at least once. A do-while loop
begins with the keyword do, followed by the statements that make up the
body of the loop.
SYNTAX:

Do

<loop body>
}while (<loop condition>);

Example:

public class DoWhileLoopDemo {


public static void main(String[] args)
{

int count = 1;
System.out.println("Printing Numbers from 1 to 10"); do {
System.out.println(count++);
} while (count <= 10);
}

OUTPUT:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
FOR LOOPS
THE FOR LOOP IS A LOOPING CONSTRUCT WHICH CAN EXECUTE A SET OF INSTRUCTIONS A
SPECIFIEDNUMBER OF TIMES. IT‘S A COUNTER CONTROLLED LOOP. A FOR STATEMENT CONSUMES THE
INITIALIZATION, CONDITION AND INCREMENT/DECREMENT IN ONE LINE. IT IS THE ENTRY CONTROLLED
LOOP.

SYNTAX:
for (<initialization>; <loop condition>; <increment expression>)

<LOOP BODY>
}

The first part of a for statement is a starting initialization, which executes


once before the loop begins. The <initialization> section can also be a
comma-separatedlist of expression statements.
The second part of a for statement is a test expression. As long as the
expression istrue, the loop will continue. If this expression is evaluated as
false the first time, theloop will never be executed.
The third part of the for statement is the body of the loop. These are the
instructionsthat are repeated each time the program executes the loop.
The final part of the for statement is an increment expression that
automaticallyexecutes after each repetition of the loop body. Typically, this
statement changes the value of the counter, which is then tested to see if the
loop should continue.
EXMPLE:
public class ForLoopDemo {
public static void main(String[] args)
{

System.out.println("Printing Numbers from 1 to 10");


for (int count = 1; count <= 10; count++)
{

System.out.println(count);
}

OUTPUT:
Printing Numbers from 1 to 10
1
2
3
4
5
6
7
8
9
10
ENHANCED FOR LOOP OR FOR- EACH LOOP:
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
The for-each loop is used to traverse array or collection in java.
It is easier to use than simple for loop because we don't need to increment
value and usesubscript notation.
It works on elements basis not index.
It returns element one by one in the defined variable.
Syntax:

for(declaration : expression)

//Statements

Declaration: The newly declared block variable, which is of a type


compatible with the elements of the array you are accessing. The variable
will be available within the for block and its value would be the same as the
current array element.
Expression: This evaluates to the array you need to loop through. The
expression can be an array variable or method call that returns an array.
EXAMPLE:
PUBLIC CLASS TEST {
public static void main(String args[])
{

int [] numbers = {10, 20, 30, 40, 50};


for(int x : numbers )
{

System.out.print( x );

System.out.print(",");

System.out.print("\n\n");
String [] names ={"B", "C", "C++", "JAVA"};
for( String name : names )
{

System.out.print( name ); System.out.print(",");}

Output: 10,20,30,40,50, B,C,C++,JAVA

TRANSFER STATEMENTS / LOOP CONTROL STATEMENTS/JUMP STATEMENTS)

1.​ break statement


2.​ continue statement

1.​ USING BREAK STATEMENT:


✔​ The break keyword is used to stop the entire loop. The
break keyword must beused inside any loop or a switch
statement.
✔​ The break keyword will stop the execution of the
innermost loop and start executingthenext line of code
after the block.
SYNTAX:
The syntax of a break is a single statement inside any loop:
FLOWCHART:

EXAMPLE:

public class Test {


public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x :
numbers ) { if( x == 30 ) { break;
}

System.out.print( x ); System.out.print("\n");
}

Output:
10
20

Using continue Statement:


The continue keyword can be used in any of the loop control structures. It
causes theloop to immediately jump to the next iteration of the loop.
The Java continue statement is used to continue loop. It continues the
current flow of the program and skips the remaining code at specified
condition. In case of inner loop, it continues only inner loop.
SYNTAX:
The syntax of a continue is a single statement inside any loop:
CONTINUE;
Example:

public class Test {

public static void main(String


args[]) {int [] numbers = {10, 20,
30, 40, 50};
for(int x : numbers )
{

if( x == 30 )
{

continue;
}

System.out.pri
nt( x );
System.out.pri
nt("\n");
}

OUTPUT:
10
20
40
50
DEFINING CLASSES AND OBJECTS

A class is a collection of similar objects and it contains data and methods


that operate on that data. In other words ― Class is a blueprint or
template for a set of objects that share a common structure and a
common behavior.

DEFINING A CLASS:
The keyword class is used to define a class.

Rules to be followed:
1.​ Classes must be enclosed in parentheses.
2.​ The class name, superclass name, instance variables and method names
may be any validJava identifiers.
3.​ The instance variable declaration and the statements of the methods
must end with ;(semicolon).
4.​ The keyword extends means derived from i.e. the class to the left of the
EXTENDS

(subclass) is derived from the class to the right of the extends (superclass).
SYNTAX TO DECLARE A CLASS:

✔​ The data, or variables, defined within a class are called instance variables.
✔​ The code to do operations is contained within methods.
✔​ Collectively, the methods and variables defined within a class are called members
of theclass.
✔​ Variables defined within a class are called instance variables because
each instance of theclass (that is, each object of the class) contains its
own copy of these variables.
✔​ Thus, the data for one object is separate and unique from the data for another.

✔​ EXAMPLE:
Program Explanation:

Class​ : keyword that


initiates a class definition Box​ :
class name
Double​ : primitive data type
Height, depth, width:
Instance variables Void
​ : return
type of the method
Volume() : method name that has no parameters

DEFINING OBJECTS

An Object is an instance of a class. It is a blending of methods and data.

It is a structured set of data with a set of operations for manipulating that data.
The methods are the only gateway to access the data. In other words, the
methods and dataare grouped together and placed in a container called
Object.
CHARACTERISTICS OF AN OBJECT:
An object has three characteristics:
1)​ State: represents data (value) of an object.
2)​ Behavior: represents the behavior (functionality) of an
object such as deposit, withdraw etc.
3)​ Identity: Object identity is an unique ID used internally
by the JVM to identify each object uniquely.
4)​ For Example: Pen is an object. Its name is Reynolds,
color is white etc. known
state. It is used to write, so writing is its behavior.
CREATING OBJECTS:
Obtaining objects of a class is a two-step process:
1.​ Declare a variable of the class type – this variable does not define an
object. Instead,it is simply a variable that can refer to an object.
2.​ Use new operator to create the physical copy of the object and
assign the referenceto the declared variable.

NOTE: The new operator dynamically allocates memory for an object and returns a
referenceto it. This reference is the address in memory of the object allocated by new.
Advantage of using new operator: A program can create as many as objects it needs
duringthe execution of the program.

SYNTAX:

Example:

box b1=new
box();(or) box b2;
b2=new box();
ACCESSING CLASS MEMBERS:
✔​ Accessing the class members means accessing instance variable and instance
methods in a class.
✔​ To access these members, a dot (.) operator is used along with the objects.
SYNTAX FOR ACCESSING THE INSTANCE MEMBERS AND METHODS:

1.11: METHODS

DEFINITION :

Syntax: Method:
modifier Return –type method_name(parameter_list) throws exception_list
{
// method body
}

The syntax shown above includes:

modifier: It defines the access type of the method and it is optional to use.
returnType: Method may return a value.
Method_name: This is the method name. The method signature consists of
the methodname and the parameter list.
Parameter List: The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero
parameters.
method body: The method body defines what the method does with statements.
METHOD CALLING (EXAMPLE FOR METHOD THAT TAKES PARAMETERS AND RETURNING
VALUE):

✔​ For using a method, it should be called.


✔​ A method may take any no. of arguments.
✔​ A parameter is a variable defined by a method that receives a
value when the method is called. For example, in square( ), i is
a parameter.
✔​ An argument is a value that is passed to a method when it is
invoked. For example, square(100) passes 100 as an argument.
Inside square( ), the parameter i receives that value.
✔​ There are two ways in which a method is called.
•​ calling a method that returns a value or
•​ calling a method returning nothing (no return value).
✔​ The process of method calling is simple. When a program invokes a
method, the programcontrol gets transferred to the called method.
✔​ This called method then returns control to the caller in two conditions, when:
1.​ return statement is executed.
2.​ reaches the method ending closing
brace.

1.13: ACCESS SPECIFIERS


DEFINITION:

Java classes,​ fields,​ constructors and methods​can​ have​ one


​ of​ four different
accessmodifiers:
1.​ Public
2.​ Private
3.​ Protected
4.​ Default (package)
1.​ PUBLIC (ANYTHING DECLARED AS PUBLIC CAN BE ACCESSED FROM ANYWHERE):
A variable or method declared/defined with the public modifier can be
accessed anywhere in the program through its class objects, through its
subclass objects andthrough the objects of classes of other packages
also.
2.​ PRIVATE (ANYTHING DECLARED AS PRIVATE CAN’T BE SEEN OUTSIDE OF THE CLASS):
The instance variable or instance methods declared/initialized as private
can be accessedonly by its class. Even its subclass is not able to access
the private members.
3.​ PROTECTED (ANYTHING DECLARED AS PROTECTED CAN BE
ACCESSED BY CLASSES IN THE SAMEPACKAGE AND SUBCLASSES IN
THE OTHER PACKAGES):

The protected access specifier makes the instance variables and instance
methods visibleto all the classes, subclasses of that package and
subclasses of other packages.
4.​ DEFAULT (CAN BE ACCESSED ONLY BY THE CLASSES IN THE SAME PACKAGE):
The default access modifier is friendly. This is similar to public modifier
except only theclasses belonging to a particular package knows the
variables and methods.

EXAMPLE: ILLUSTRATING THE VISIBILITY OF ACCESS SPECIFIERS


Z:\MYPACK\FIRSTCLASS.JAVA
PACKAGE MYPACK; PUBLIC CLASS

FirstClas
{

public String i="I am public variable";


protected String j="I am protected
variable";​
private String k="I am private variable";
String r="I dont have any modifier";
}
Z:\MYPACK2\SECONDCLASS.JAVA
package MyPack2;
import MyPack.FirstClass;
class Second
Class extends FirstClass {
void method()
{

System.out.println(i);​ ​// No Error: Will print "I am public


variable". System.out.println(j);​ // No Error: Will print “I am protected
variable”. System.out.println(k); // Error: k has private access in FirstClass
System.out.println(r); // Error: r is not public in FirstClass; cannot be accessed
//​ from outside package
}

public static void main(String arg[])


{

SecondClass obj=new
SecondClass(); obj.method();
}

Output:

I am public variable
I am protected variable
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code -
k has private access in MyPack.FirstClass
“static” MEMBERS:
STATIC MEMBERS ARE DATA MEMBERS (VARIABLES) OR METHODS THAT BELONG TO A STATIC OR
NON-STATIC CLASS RATHER THAN TO THE OBJECTS OF THE CLASS. HENCE IT IS NOT NECESSARY
TO CREATE OBJECT OF THAT CLASS TO INVOKE STATIC MEMBERS.

The static can be:


1.​ variable (also known as class variable)
2.​ method (also known as class method)
3.​ block
4.​ nested class

STATIC VARIABLE:
✔​ When a member variable is declared with the static keyword, then it
is called static variable and it can be accessed before any objects of
its class are created, and without reference to any object.
✔​ Syntax to declare a static variable:
[ACCESS_SPEFIER] STATIC DATA_TYPE INSTANCE_VARIABLE;
✔​ When a static variable is loaded in memory (static pool) it creates only a
single copy of static variable and shared among all the objects of the
class.
✔​ A static variable can be accessed outside of its class directly by
the class name anddoesn‘t need any object.
SYNTAX : <CLASS-NAME>.<VARIABLE-NAME>
Advantages of static variable

✔​ It makes your program memory efficient (i.e., it saves memory).

STATIC METHOD:
If a method is declared with the static keyword , then it is known as static
method.

A static method belongs to the class rather than the object of a class.

A static method can be invoked without the need for creating an instance of a class.

A static method can access static data member and can change the value of it.
O​ SYNTAX: (DEFINING STATIC METHOD)

o​ Syntax to access static method:

Methods declared as static have several restrictions:


✔​ They can only directly call other static methods.
✔​ They can only directly access static data.
✔​ They cannot refer to this or super in any way.

STATIC BLOCK:
Static block is used to initialize the static data member like constructors helps to
initialize instance members and it gets executed exactly once, when the class is
first loaded.

It is executed before main method at the time of class loading in JVM.

Syntax:

The following example shows a class that has a static method, some static variables,
and a static

initialization block:

// Demonstrate static variables, methods, and blocks.

class Student
{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object
public class TestStaticMembers{
static
{
System.out.println(―*** STATIC MEMBERS – DEMO ***‖);
}
public static void main(String args[])
{
Student.change(); //calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Here is the output of this program:
*** STATIC MEMBERS – DEMO ***
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

1.12: CONTRUCTORS
DEFINITION:

Rules for creating constructor:


1.​ Constructor name must be same as its class name
2.​ Constructor must have no explicit return type
3.​ Constructors can be declared public or private (for a Singleton)
4.​ Constructors can have no-arguments, some arguments and var-args;
5.​ A constructor is always called with the new operator
6.​ The default constructor is a no-arguments one;
7.​ If you don‘t write ANY constructor, the compiler will generate the default
one;
8.​ Constructors CAN‘T be static, final or abstract;
9.​ When overloading constructors (defining methods with the
same name but with different arguments lists) you must
define them with different arguments lists (as number or as
type)

WHAT HAPPENS WHEN A CONSTRUCTOR IS CALLED?

All data fields are initialized to their default value (0, false or null).
All field initializers and initialization blocks are executed, in the order in
which theyoccur in the class declaration.
If the first line of the constructor calls a second constructor, then the body of
thesecond constructor is executed.
The body of the constructor is executed.

TYPES OF CONSTRUCTORS
There are two types of constructors:
Default constructor
no-arg constructor
Parameterized constructor

DEFAULT CONSTRUCTOR
Default constructor refers to a constructor that is automatically created by
compilerin the absence of explicit constructors.
Rule: If there is no constructor in a class, compiler automaticaaly creates a default
constructor.
Purpose of Default Constructor: It is used to provide the default values to the
object members like 0, null etc. depending on the data type.

NO-ARGUMENT CONSTRUCTOR
Constructor without parameters is called no-argument constructor.
Purpose of No-Arg Constructor: It is used to provide values to be common for all objects
of the class.
Parameterized Constructor
A constructor that takes parameters is known as parameterized constructor.
Purpose of parameterized constructor
Parameterized constructor is used to provide different values to the distinct objects.
CONSTRUCTOR OVERLOADING:
Definition:

CONSTRUCTOR CHAINING:
Constructor chaining is the process of calling one constructor of a class from
another constructor of the same class or another class using the current object
of the class.It occurs through inheritance.

Ways to achieve Constructor Chaining:

We can achieve constructor chaining in two ways:

Within the same class: If we want to call the constructor from the same class, then we use
this keyword.​

From the base class: If we want to call the constructor that belongs to different classes
(parent and child classes), we use the super keyword to call the constructor from the base
class.
RULES OF CONSTRUCTOR CHAINING:
✔​ An expression that uses this keyword must be the first line of the
constructor.
✔​ Order does not matter in constructor chaining.
✔​ There must exist at least one constructor that does not use this
ADVANTAGE:
✔​ Avoids duplicate code while having multiple constructors.
✔​ Makes code more readable
DESTRUCTOR
A DESTRUCTOR, US THE NAME IMPLIES IS USED TO DESTROY THE OBJECTS THAT HAVE BEEN
CONSTRUCTOR. LIKE A CONSTRUCTOR, THE DESTRUCTOR IS A MEMBER
CREATED BY A
FUNCTION WHOSE NAME IS THE SAME AS THE

Class Name But Is Preceded By A Tilde.

For Example:- ​
~ integer( ) { }

A destructor never takes any argument nor does it return any value. It will be invoked
implicitly by the compiler upon exit from the program to clean up storage that is no longer
accessible. It is a good practice to declare destructor in a program since it releases memory
space for
future use.
Delete is used to free memory which is created by new.

Example:-

matrix : : ~ matrix( )

for(int i=0; i<11;i++)

delete p[i];

delete p;

UNIT 2

INHERITANCE

Inheritance is the mechanism in java by which one class is allow to inherit the
features (fields and methods) of another class. It is process of deriving a new class from an
existing class. A class that is inherited is called a superclass and the class that does the
inheriting is called a subclass. Inheritance represents the IS-A relationship, also known as
parent-child relationship. The keyword used for inheritance is extends.

Syntax:

class Subclass-name extends Superclass-name

{ //methods and fields }

Here, the extends keyword indicates that we are creating a new class that derives from an
existing class. Note: The constructors of the superclass are never inherited by the subclass

advantages of Inheritance:

• Code reusability — public methods of base class can be reused in derived classes

• Data hiding – private data of base class cannot be altered by derived class

• Overriding—With inheritance, we will be able to override the methods of the base class in
the derived class Example: //

Create a superclass.

BaseClass{ int a=10,b=20;

public void add(){

System.out.println(“Sum:”+(a+b));

// Create a subclass by extending class BaseClass.

Public class Main extends BaseClass

{ public void sub(){

System.out.println(“Difference:”+(a-b));

} public static void main(String[] args) {

Main obj=new Main();

/*The subclass has access to all public members of its superclass*/

obj.add(); obj.sub(); } }

Sample Output:

Sum:30
Difference:-10

In this example, Main is the subclass and BaseClass is the superclass. Main object can access
the field of own class as well as of BaseClass class i.e. code reusability.

Superclass and Subclass

●​ Superclass (Parent Class): The class whose properties and methods are inherited by
another class.
●​ Subclass (Child Class): The class that inherits the properties and methods of the
superclass.

Syntax for Inheritance

●​ Use the extends keyword to create a subclass that inherits from a superclass.

Java
Copy code
class Superclass {
// Fields, constructors, methods
}

class Subclass extends Superclass {


// Additional fields, constructors, methods
}

Example

java
Copy code
// Superclass
public class Animal {
String name;

public void eat() {


System.out.println(“This animal eats food.”);
}
}

// Subclass
public class Dog extends Animal {
public void bark() {
System.out.println(“The dog barks.”);
}
}

// Main Class to demonstrate inheritance


public class TestInheritance {
public static void main(String[] args) {
Dog dog = new Dog();
dog.name = “Buddy”;
dog.eat(); // Inherited method
dog.bark(); // Subclass-specific method
}
}

Inherited Members

●​ Fields and Methods: All non-private fields and methods of the superclass are
inherited by the subclass.
●​ Constructors: Constructors are not inherited, but the subclass can call the superclass
constructor using super().

Overriding Methods

●​ Method Overriding: A subclass can provide a specific implementation for a method


that is already defined in its superclass.
o​ Use the @Override annotation to indicate that a method is being overridden.

Java
Copy code
public class Dog extends Animal {
@Override
public void eat() {
System.out.println(“The dog eats bones.”);
}
}
The super Keyword

●​ Calling Superclass Methods: Use super.methodName() to call a method from the


superclass.
●​ Calling Superclass Constructor: Use super(arguments) to call the constructor of the
superclass.

Java
Copy code
public class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + “ eats food.”);
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name); // Call to superclass constructor
} @Override
public void eat() {
super.eat(); // Call to superclass method
System.out.println(name + “ eats bones.”);
}
}

Multiple Levels of Inheritance

●​ A subclass can be a superclass for another class, creating a multi-level inheritance


hierarchy.

Java
Copy code
class A {
// Fields and methods
}

class B extends A {
// Additional fields and methods
}

class C extends B {
// Additional fields and methods
}

Access Modifiers and Inheritance

●​ Private Members: Private fields and methods of the superclass are not accessible
directly in the subclass.
●​ Protected Members: Protected fields and methods are accessible in the subclass.
●​ Public Members: Public fields and methods are accessible everywhere.
●​ Package-Private Members: Accessible to subclasses only if they are in the same
package

Types of inheritance

Single Inheritance :

In single inheritance, a subclass inherit the features of one superclass.

Example:

class Shape{ int a=10,b=20; }

class Rectangle extends Shape{

public void rectArea(){

System.out.println(“Rectangle Area:”+(a*b));

}}
public class Main {

public static void main(String[] args) {

Rectangle obj=new Rectangle(); obj.rectArea(); } }

Multilevel Inheritance:

In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class i.e. a derived class in turn acts as a base
class for another class.

Example:

class Numbers{ int a=10,b=20;

} class Add2 extends Numbers{ int c=30;

public void sum2(){

System.out.println(“Sum of 2 nos.:”+(a+b));

} } class Add3 extends Add2{

public void sum3()

{ System.out.println(“Sum of 3 nos.:”+(a+b+c)); }

} public class Main


{ public static void main(String[] args) {

Add3 obj=new Add3();

obj.sum2();

obj.sum3(); } }

Sample Output:

Sum of 2 nos.:30

Sum of 3 nos.:60

hierarchical Inheritance:

In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one
sub class.

Example:

class Shape{

int a=10,b=20; }

class Rectangle extends Shape{

public void rectArea(){

System.out.println(“Rectangle Area:”+(a*b)); }

} class Triangle extends Shape{ public void triArea()

{ System.out.println(“Triangle Area:”+(0.5*a*b)); } }

public class Main

{ public static void main(String[] args) {

Rectangle obj=new Rectangle();

obj.rectArea();

Triangle obj1=new Triangle();

obj1.triArea(); } }

Sample Output:

Rectangle Area:200

Triangle Area:100.0
Multiple inheritance

Java does not allow multiple inheritance:

• To reduce the complexity and simplify the language

• To avoid the ambiguity caused by multiple inheritance

For example, Consider a class C derived from two base classes A and B. Class C inherits A
and B features. If A and B have a method with same signature, there will be ambiguity to call
method of A or B class. It will result in compile time error.

Class A{

void msg(){

System.out.println(“Class A”);} }

class B{

void msg()

{System.out.println(“Class B “);} }

class C extends A,B{//suppose if it were

Public Static void main(String args[]){

C obj=new C(); obj.msg();//Now which msg() method would be invoked? } }

Sample Output: Compile time error

Direct implementation of multiple inheritance is not allowed in Java. But it is achievable


using Interfaces. The concept about interface is discussed in chapter.2.7.

access control in Inheritance

The following rules for inherited methods are enforced –

• Variables declared public or protected in a superclass are inheritable in subclasses.

• Variables or Methods declared private in a superclass are not inherited at all.

• Methods declared public in a superclass also must be public in all subclasses.

• Methods declared protected in a superclass must either be protected or public in subclasses;


they cannot be private.

Example:

// Create a superclass
class A{

int x; // default specifier

private int y; // private to A

public void set_xy(int a,int b){

x=a; y=b; } }

// A’s y is not accessible here.

Class B extends A{

public void add(){

System.out.println(“Sum:”+(x+y)); //Error: y has private access in A – not inheritable } }

class Main{

public static void main(String args[]){

B obj=new B();

obj.set_xy(10,20);

obj.add(); } }

In this example since y is declared as private, it is only accessible by its own class members.
Subclasses have no access to it.

UsIng sUper

The super keyword refers to immediate parent class object. Whenever you create the
instance of subclass, an instance of parent class is created implicitly which is referred by
super reference variable.

• It an be used to refer immediate parent class instance variable when both parent and child
class have member with same name

• It can be used to invoke immediate parent class method when child class has overridden
that method.

• super() can be used to invoke immediate parent class constructor.

Use of super with variables:

When both parent and child class have member with same name, we can use super keyword
to access ubcla of parent class.

Example:
class SuperCls {

int x = 20; }

/* sub class SubCls extending SuperCls */

class SubCls extends SuperCls {

int x = 80;

void display() {

System.out.println(“Super Class x: “ + super.x); //print x of super class

System.out.println(“Sub Class x: “ + x); //print x of subclass }

} /* Driver program to test */

class Main {

public static void main(String[] args)

{ SubCls obj = new SubCls();

obj.display(); } }

sample Output:

Super Class x: 20 Sub Class x: 80

In the above example, both base class and subclass have a member x. We could access x of
base class in ubclass using super keyword.

Use of super with methods:

The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class (Method Overriding).

Class SuperCls { int x = 20;

void display(){ //display() in super class

System.out.println(“Super Class x: “ + x); }

} /* sub class SubCls extending SuperCls */

class SubCls extends SuperCls {

int x = 80;

void display() //display() redefined in sub class – method overriding

{ System.out.println(“Sub Class x: “ + x);


super.display(); // invoke super class display() } }

/* Driver program to test */

class Main {

public static void main(String[] args)

{ SubCls obj = new SubCls();

obj.display(); } }

Sample Output:

Sub Class x: 80 Super Class x: 20​

In the above example, if we only call method display() then, the display() of sub class gets
invoked. But with the use of super keyword, display() of superclass could also be invoked.

Use of super with constructors: The super keyword can also be used to invoke the parent
class constructor. Syntax:

super();

• super() if present, must always be the first statement executed inside a subclass constructor.

• When we invoke a super() statement from within a subclass constructor, we are invoking
the immediate super class constructor

Example:

class SuperCls {

SuperCls(){

System.out.println(“In Super Constructor”); } }

/* sub class SubCls extending SuperCls */

class SubCls extends SuperCls {

SubCls()

{ super();

System.out.println(“In Sub Constructor”); } }

/* Driver program to test */

class Main {

public static void main(String[] args)


{

SubCls obj = new SubCls(); }

INTERFACES

Interfaces An interface is a reference type in Java. It is similar to class. It is a collection of


abstract methods. Along with abstract methods, an interface may also contain constants,
default methods, static methods, and nested types. Method bodies exist only for default
methods and static methods.

An interface is similar to a class in the following ways:

• An interface can contain any number of methods.

• An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.

• The byte code of an interface appears in a .class file.

• Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.

Interfaces vs. Abstract Classes in Java

Definitions

●​ Interface: A reference type in Java, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Interfaces
cannot contain instance fields.
●​ Abstract Class: A class that cannot be instantiated on its own and may contain
abstract methods (methods without implementation) as well as concrete methods
(methods with implementation).

When to Use

●​ Interfaces: Use when you want to define a contract that multiple classes can
implement, without enforcing a specific inheritance hierarchy.
●​ Abstract Classes: Use when you want to provide a common base class with some
shared implementation that other classes can inherit from and extend.

Syntax

●​ Interface:

java
Copy code
public interface MyInterface {
void abstractMethod();
default void defaultMethod() {
// Default implementation
}
static void staticMethod() {
// Static implementation
}
}

●​ Abstract Class:

java
Copy code
public abstract class MyAbstractClass {
abstract void abstractMethod(); // Abstract method (no implementation)

void concreteMethod() {
// Concrete method (with implementation)
}
}

Key Differences

1.​ Instantiation:
o​ Interface: Cannot be instantiated.
o​ Abstract Class: Cannot be instantiated directly.
2.​ Methods:
o​ Interface: Can contain abstract methods, default methods, and static methods.
o​ Abstract Class: Can contain abstract methods and concrete methods.
3.​ Fields:
o​ Interface: Can only have static final fields (constants).
o​ Abstract Class: Can have instance fields.
4.​ Inheritance:
o​ Interface: A class can implement multiple interfaces.
o​ Abstract Class: A class can extend only one abstract class (single
inheritance).
5.​ Access Modifiers:
o​ Interface: Methods are implicitly public; fields are implicitly public, static,
and final.
o​ Abstract Class: Can have any access modifier (public, protected, private) for
methods and fields.
6.​ Constructor:
o​ Interface: Cannot have constructors.
o​ Abstract Class: Can have constructors, which can be called by subclasses.

Example Usage

●​ Interface:

java
Copy code
public interface Animal {
void eat();
void sleep();
}

public class Dog implements Animal {


@Override
public void eat() {
System.out.println(“Dog eats”);
}

@Override
public void sleep() {
System.out.println(“Dog sleeps”);
}
}

●​ Abstract Class:

java
Copy code
public abstract class Animal {
abstract void eat();

void sleep() {
System.out.println(“Animal sleeps”);
}
}

public class Dog extends Animal {


@Override
void eat() {
System.out.println(“Dog eats”);
}
}

Multiple Inheritance

●​ Interface: Supports multiple inheritance of type. A class can implement multiple


interfaces.

Java
Copy code
public class Dog implements Animal, Pet {
// Implement methods from both interfaces
}

●​ Abstract Class: Does not support multiple inheritance of type. A class can extend
only one class.
Java
Copy code
public class Dog extends Canine {
// Can extend only one superclass
}

Use Cases

●​ Interfaces:
o​ When multiple unrelated classes need to implement a set of methods (e.g.,
Comparable, Runnable).
o​ To define a contract for what a class can do, without dictating how it does it.
o​ To achieve multiple inheritance of type.
●​ Abstract Classes:
o​ When creating a base class that should not be instantiated on its own.
o​ To provide common functionality to subclasses.
o​ When you want to define some methods that should be shared by all
subclasses while leaving others abstract.

Uses of interface:

• Since java does not support multiple inheritance in case of class, it can be achieved by using
interface.

• It is also used to achieve loose coupling

. • Interfaces are used to implement abstraction.

Defining an Interface

An interface is defined much like a class.

Syntax:

accessspecifier interface interfacename {

return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

type final-varname1 = value;

type final-varname2 = value; // ...

return-type method-nameN(parameter-list);

type final-varnameN = value; }


When no access specifier is included, then default access results, and the interface is only
available to other members of the package in which it is declared. When it is declared as
public, the interface can be used by any other code.

• The java file must have the same name as the interface.

• The methods that are declared have no bodies. They end with a semicolon after the
parameter list. They are abstract methods; there can be no default implementation of any
method specified within an interface.

• Each class that includes an interface must implement all of the methods.

• Variables can be declared inside of interface declarations. They are implicitly final and
static, meaning they cannot be changed by the implementing class. They must also be
initialized.

• All methods and variables are implicitly public.

Sample Code: The following code declares a simple interface Animal that contains two
methods called eat() and travel() that take no parameter.

/* File name : Animal.java */

interface Animal {

public void eat();

public void travel(); }

Implementing an Interface

Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, the ‘implements’ clause is included in a class definition and then the
methods defined by the interface are created.

Syntax:

class classname [extends superclass] [implements interface [,interface...]]

{ // class-body }

properties of java interface

• If a class implements more than one interface, the interfaces are separated with a comma.

• If a class implements two interfaces that declare the same method, then the same method
will be used by clients of either interface.

• The methods that implement an interface must be declared public.


• The type signature of the implementing method must match exactly the type signature
specified in the interface definition

Rules

• A class can implement more than one interface at a time.

• A class can extend only one class, but can implement many interfaces.

• An interface can extend another interface, in a similar way as a class can extend another
class.

Sample Code 1:

The following code implements an interface Animal shown earlier.

/* File name : MammalInt.java */

public class Mammal implements Animal {

public void eat()

{ System.out.println(“Mammal eats”);

} public void travel()

{ System.out.println(“Mammal travels”);

} public int noOfLegs() { return 0;

} public static void main(String args[]) { Mammal m = new Mammal();

m.eat();

m.travel(); } }

Output: Mammal eats

Mammal travels

It is both permissible and common for classes that implement interfaces to define additional
members of their own. In the above code, Mammal class defines additional method called
noOfLegs().

Sample Code 2:

The following code initially defines an interface ‘Sample’ with two members. This interface
is implemented by a class named ‘testClass’.

Import java.io.*;

// A simple interface
interface Sample {

final String name = “Shree”;

void display(); }

// A class that implements interface.

Public class testClass implements Sample { public void display()

{ System.out.println(“Welcome”);

} public static void main (String[] args)

{ testClass t = new testClass();

t.display();

System.out.println(name); } }

Output: Welcome

Shree

nested Interface

An interface can be declared as a member of a class or another interface. Such an interface is


called a member interface or a nested interface. A nested interface can be declared as public,
private, or protected.

Sample Code:

interface MyInterfaceA

{ void display();

interface MyInterfaceB

{ void myMethod(); }

} public class NestedInterfaceDemo1 implements MyInterfaceA.MyInterfaceB

{ public void myMethod()

{ System.out.println(“Nested interface method”);

} public static void main(String args[])

{ MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo1();

obj.myMethod(); } }

Output: Nested interface method


Differences between classes and interfaces

Both classes and Interfaces are used to create new reference types. A class is a collection of
fields and methods that operate on fields. A class creates reference types and these reference
types are used to create objects. A class has a signature and a body. The syntax of class
declaration is shown below:

class class_Name extends superclass implements interface_1,….interface_n

// class signature { //body of class. }

Signature of a class has class’s name and information that tells whether the class has inherited
another class. The body of a class has fields and methods that operate on those fields. A Class
is created using a keyword class.

When a class is instantiated, each object created contains a copy of fields and methods with
them. The fields and members declared inside a class can be static or nonstatic. Static
members value is constant for each object whereas, the non-static members are initialized by
each object differently according to its requirement.

Members of a class have access specifiers that decide the visibility and accessibility of the
members to the user or to the subclasses. The access specifiers are public, private and
protected. A class can be inherited by another class using the access specifier which will
decide the visibility of members of a superclass (inherited class) in a subclass (inheriting
class).

An interface has fully abstract methods (methods with nobody). An interface is syntactically
similar to the class but there is a major difference between class and interface that is a class
can be instantiated, but an interface can never be instantiated.

An interface is used to create the reference types. The importance of an interface in Java is
that, a class can inherit only a single class. To circumvent this restriction, the designers of
Java introduced a concept of interface. An interface declaration is syntactically similar to a
class, but there is no field declaration in interface and the methods inside an interface do not
have any implementation. An interface is declared using a keyword interface.
Inheritance between concrete (non-abstract) and abstract classes use extends keyword. It is
possible to extend only one class to another. Java does not support multiple inheritance.
However, multilevel inheritance i.e., any number of classes in a ladder is possible. For
example, in the following code class C extends the class B, where the class B extends class
A.

class A {}

class B extends A { }

class C extends B { }

Inheritance between classes (including abstract classes) and interfaces, use implements
keyword.

To support multiple inheritance, it uses interfaces. So after implements keyword, there can be
any number of interfaces. For example, in the following code, class B extends only one class
A and two interfaces I1 and I2.

Interface I1 {}

interface I2 {}

class A class B extends A implements I1, I2 { }

Inheritance between two interfaces, is possible with the use of extends keyword only.

For example, in the following code, interface I2 extends the interface I1.

Interface I1 { }

interface I2 extends I1{ }

nested classes

In Java, a class can have another class as its member. The class written within another class
is called the nested class, and the class that holds the inner class is called the outer class.

Java inner class is defined inside the body of another class. Java inner class can be declared
private, public, protected, or with default access whereas an outer class can have only public
or default access. The syntax of nested class is shown below:

class Outer_Demo { class Nested_Demo { } } types of nested classes There are two types of
nested classes in java. They are non-static and static nested classes. The non-static nested
classes are also known as inner classes.

• Non-static nested class (inner class)

○ Member inner class

○ Method Local inner class

○ Anonymous inner class


• Static nested class

Inner classes (nOn-statIc nested classes)

Inner classes can be used as the security mechanism in Java. Normally, a class cannot be
related with the access specifier private. However if a class is defined as a member of other
class, then the inner class can be made private. This class can have access to the private
members of a class.

The three types of inner classes are

• Member Inner Class

• Method-local Inner Class

• Anonymous Inner Class

Member Inner class

The Member inner class is a class written within another class. Unlike a class, an inner class
can be private and once you declare an inner class private, it cannot be accessed from an
object outside the class.

The following program is an example for member inner class.

Class Outer_class { int n=20;

private class Inner_class {

public void display() {

System.out.println(“This is an inner class”);

System.out.println(“n:”+n);

} } void print_inner()

{ Inner_class inn = new Inner_class();

inn.display(); }

}
public class Myclass

{ public static void main(String args[])

{ Outer_class out= new Outer_class();

out.print_inner(); } }

Output: This is an inner class

Method-local Inner class

In Java, a class can be written within a method. Like local variables of the method, the scope
of the inner class is restricted within the method. A method-local inner class can be
instantiated only within the method where the inner class is defined. The following program
shows how to use a method-local inner class. The following program is an example for
Method-local Inner Class

public class Outer_class {

void Method1() { int n = 100;

class MethodInner_class {

public void display() {

System.out.println(“This is method inner class “);

System.out.println(“n:”+n); }

} MethodInner_class inn= new MethodInner_class(); inn.display();

} public static void main(String args[])

{ Outer_class out = new Outer_class();

out.Method1(); } }

Output: This is method inner class n: 100

anonymous Inner class

An inner class declared without a class name is known as an anonymous inner class. The
anonymous inner classes can be created and instantiated at the same time. Generally, they are
used whenever you need to override the method of a class or an interface. The syntax of an
anonymous inner class is as follows –

abstract class Anonymous_Inner {

public abstract void Method1(); }

The following program is an example for anonymous inner class.


Public class Outer_class {

public static void main(String args[]) {

Anonymous_Inner inn = new Anonymous_Inner() {

public void Method1()

{ System.out.println(“This is the anonymous inner class”); }

}; inn.Method1(); } }

Output: This is the anonymous inner class

static nested class

A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods of
the outer class. Instantiating a static nested class is different from instantiating an inner class.

The following program shows how to use a static nested class.

Public class Outer_class {

static class inner_class{

public void Method1() {

System.out.println(“This is the nested class”); } }

public static void main(String args[]) {

Outer_class.inner_class obj = new Outer_class.inner_class();

obj.Method1(); } }

Output: This is the nested class

advantage of java inner classes:

There are basically three advantages of inner classes in java. They are as follows:

• Nested classes represent a special type of relationship that is it can access all the members
of outer class including private.

• Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.

• It provides code optimization. That is it requires less code to write.


PACKAGES

A Package can be defined as a collection of classes, interfaces, enumerations and annotations,


providing access protection and name space management.

⎫ Package can be categorized in two form:

1. Built-in package

2. user-defined package.

Advantage of Package:

∙ Package is used to categorize the classes and interfaces so that they can be easily
maintained.

∙ Package provides access protection.

∙ Package removes naming collision.

∙ To bundle classes and interface

∙ The classes of one package are isolated from the classes of another package

∙ Provides reusability of code

∙ We can create our own package or extend already available package

2.10.1: CREATING USER DEFINED PACKAGES:


Java package created by user to categorize their project’s classes and interface are known as
user-defined packages.

⎫ When creating a package, you should choose a name for the package.

⎫ Put a package statement with that name at the top of every source file that contains the
classes and interfaces.

⎫ The package statement should be the first line in the source file.

⎫ There can be only one package statement in each source file

Syntax: package package_name.[sub_package_name];

public class classname

{ …….. …….. }

⎫ Steps involved in creating user-defined package:

1. Create a directory which has the same name as the package.

2. Include package statement along with the package name as the first statement in the
program.

3. Write class declarations.

4. Save the file in this directory as “name of class.java”.

5. Compile this file using java compiler.

⎫ Example: package pack;

public class class1

{ public static void greet()

{ System.out.println(“Hello”); }

To create the above package,

1. Create a directory called pack.

2. Open a new file and enter the code given above.

3. Save the file as class1.java in the directory.

4. A package called pack has now been created which contains one class class1.
2.10.2: ACCESSING A PACKAGE (using “import” keyword):

∙ The import keyword is used to make the classes and interface of another package accessible
to the current package.

Syntax:

import package1[.package2][.package3].classname or *;

There are three ways to access the package from outside the package.

1. import package.*;

2. import package.classname;

3. fully qualified name.

Using packagename.*

∙ If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.

Using packagename.classname

∙ If you import package.classname then only declared class of this package will be accessible.

⎫ Using fully qualified name

∙ If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.

Example :

greeting.java (create a folder named “pack” in F:\ and save )

package pack;

public class greeting{ public static void greet()

{ System.out.println(“Hello! Good Morning!”); } }

FactorialClass.java (create a folder named “Factorial” inside F:\pack and save)

package Factorial;

public class FactorialClass

public int fact(int a) {

if(a==1) return 1;
else return a*fact(a-1); }

ImportClass.java (save the file in F:\ )

import java.lang.*; // using import package.*

import pack.Factorial.FactorialClass; // using import package.subpackage.class;

import java.util.Scanner;

public class ImportClass

{ public static void main(String[] arg)

{ int n; Scanner in=new Scanner(System.in);

System.out.println(“Enter a Number: “);

n=in.nextInt(); pack.greeting p1=new pack.greeting(); // using fully qualified name

p1.greet();

FactorialClass fobj=new FactorialClass();

System.out.println(“Factorial of “+n+” = “+fobj.fact(n));

System.out.println(“Power(“+n+”,2) = “+Math.pow(n,2));

}}

Output: F:\>java ImportClass

Enter a Number: 5

Hello! Good Morning!

Factorial of 5 = 120

Power(5,2) = 25.0

Understanding CLASSPATH in Java Packages

What is CLASSPATH?

●​ CLASSPATH is an environment variable used by the Java Virtual Machine (JVM)


and other Java tools to locate class files.
●​ It tells the JVM where to look for user-defined classes and packages.
●​ CLASSPATH can include directories, JAR files, and ZIP files.

Setting CLASSPATH
●​ CLASSPATH can be set in several ways:
o​ Command Line: Using the -cp or -classpath option when running Java
applications.

Copy code
java -cp .:/path/to/classes:/path/to/jarfile.jar MyClass

o​ Environment Variable: Setting the CLASSPATH environment variable in


your operating system

Copy code
export CLASSPATH=.:/path/to/classes:/path/to/jarfile.jar

Components of CLASSPATH

●​ Current Directory (.): Including . in CLASSPATH allows the JVM to look for
classes in the current directory.
●​ Directories: Specify directories where compiled classes (.class files) are located.
●​ JAR Files: Specify JAR files that contain compiled classes and other resources.

Using Packages with CLASSPATH

●​ Packages: In Java, packages are used to group related classes and interfaces.
o​ Example: If you have a class MyClass in a package com.example, the
directory structure should be com/example/MyClass.class.
●​ Directory Structure: The CLASSPATH should include the parent directory of the
package structure.
o​ Example: If MyClass is in com/example, and the directory structure is
/myproject/com/example/MyClass.class, then /myproject should be in the
CLASSPATH.

Example

Assume the following directory structure:

vbnet
Copy code
/myproject
├── com
│ └── example
│ └── MyClass.class
└── lib
└── some-library.jar

To run MyClass, you can set the CLASSPATH as follows:


●​ Command Line:

sh
Copy code
java -cp /myproject:/myproject/lib/some-library.jar com.example.MyClass

●​ Environment Variable:

sh
Copy code
export CLASSPATH=/myproject:/myproject/lib/some-library.jar
java com.example.MyClass

Best Practices

●​ Avoid Hardcoding CLASSPATH: Use build tools like Maven or Gradle to manage
dependencies and CLASSPATH.
●​ Use Wildcards: In the CLASSPATH, you can use * to include all JAR files in a
directory.

Sh
Copy code
java -cp “lib/*” com.example.MyClass

Understanding and properly setting the CLASSPATH is crucial for successfully running Java
applications, especially when dealing with packages and external libraries.

Importing Packages in Java

What is a Package?

●​ Package: A package in Java is a namespace that organizes a set of related classes and
interfaces. Using packages helps avoid name conflicts and makes it easier to locate
and use classes.

Default Package

●​ Classes can be part of the default package if they are not explicitly declared in a
package. However, using the default package is not recommended for larger
applications because it can lead to naming conflicts and difficulties in managing the
code.

Declaring a Package

●​ To declare a package, use the package keyword at the top of your Java file.

Java
Copy code
package com.example.mypackage;
Importing Packages

●​ Import Statement: To use classes and interfaces from other packages, you need to
import them using the import statement.
o​ Single Type Import: Imports a specific class.

Java
Copy code
import java.util.List;

o​ Type Import on Demand (Wildcard Import): Imports all classes from a


package.

Java
Copy code
import java.util.*;

o​ Static Import: Imports static members (fields and methods) of a class.

Java
Copy code
import static java.lang.Math.*;

Using Imported Classes

●​ After importing a class, you can use it directly without specifying its fully qualified
name.

java
Copy code
import java.util.List;

public class MyClass {


public static void main(String[] args) {
List<String> myList = new ArrayList<>();
// Use myList as needed }}

Fully Qualified Name

●​ Instead of using the import statement, you can use the fully qualified name of the
class each time you refer to it. This approach is less common due to verbosity.

Java
Copy code
public class MyClass {
public static void main(String[] args) {
java.util.List<String> myList = new java.util.ArrayList<>();
// Use myList as needed
}
}
Importing Custom Packages

●​ For custom packages, ensure that the directory structure matches the package name.
o​ Example: If the package name is com.example.mypackage, the directory
structure should be com/example/mypackage/MyClass.java.
●​ Compile the classes with the correct directory structure.

Sh
Copy code
javac com/example/mypackage/MyClass.java

●​ Import and use custom packages in your Java files.

Java
Copy code
import com.example.mypackage.MyClass;

public class Test {


public static void main(String[] args) {
MyClass obj = new MyClass();
// Use obj as needed
}
}

Avoiding Name Conflicts

●​ If two packages contain classes with the same name, you can avoid conflicts by using
the fully qualified name for at least one of them.

Java
Copy code
import com.example.package1.MyClass;
import com.example.package2.MyClass;

public class Test {


public static void main(String[] args) {
MyClass obj1 = new MyClass(); // from package1
com.example.package2.MyClass obj2 = new com.example.package2.MyClass();
// from package2
// Use obj1 and obj2 as needed }}

​ ​
UNIT 4

EXCEPTION HANDLING AND MULTITHREADING

An Exception is an event that occurs during program execution which disrupts the normal
flow of a program. It is an object which is thrown at runtime. Occurrence of any kind of
exception in java applications may result in an abrupt termination of the JVM or simply the
JVM crashes.

In Java, an exception is an object that contains:

o Information about the error including its type

o The state of the program when the error occurred

o Optionally, other custom information

:Exception Hierarchy

All exceptions and errors extend from a common java.lang.Throwable parent class.

The Throwable class is further divided into two classes:

1. Exceptions and

2. Errors.

Exceptions: Exceptions represents errors in the Java application program, written by the user.
Because the error is in the program, exceptions are expected to be handled, either
∙ Try to recover it if possible

∙ Minimally, enact a safe and informative shutdown.

Sometimes it also happens that the exception could not be caught and the program may get
terminated. Eg. ArithmeticException

An exception can occur for many different reasons. Following are some scenarios where an
exception occurs. ∙ A user has entered an invalid data.

∙ A file that needs to be opened cannot be found.

∙ A network connection has been lost in the middle of communications or the JVM has run
out of memory. Some of these exceptions are caused by user error, others by programmer
error, and others by physical resources that have failed in some manner.
Errors: Errors represent internal errors of the Java run-time system which could not be
handled easily. Eg. OutOfMemoryError.

What is exception handling?

Exception Handling is a mechanism to handle runtime errors, such as


ClassNotFoundException, IOException, SQLException, RemoteException etc. by taking the
necessary actions, so that normal flow of the application can be maintained.

Advantage of using Exceptions:

∙ Maintains the normal flow of execution of the application.

∙ Exceptions separate error handling code from regular code.

o Benefit: Cleaner algorithms, less clutter

∙ Meaningful Error reporting.

∙ Exceptions standardize error handling.

try Block:

⎫ The java code that might throw an exception is enclosed in try block. It must be used within
the method and must be followed by either catch or finally block.

⎫ If an exception is generated within the try block, the remaining statements in the try block
are not executed.
¬ catch Block:

⎫ Exceptions thrown during execution of the try block can be caught and handled in a catch
block.

⎫ On exit from a catch block, normal execution continues and the finally block is executed.

¬ finally Block:

A finally block is always executed, regardless of the cause of exit from the try block, or
whether any catch block was executed.

⎫ Generally finally block is used for freeing resources, cleaning up, closing connections etc.

⎫ Even though there is any exception in the try block, the statements assured by finally block
are sure to execute.

⎫ Rule:

∙ For each try block there can be zero or more catch blocks, but only one finally block.

∙ The finally block will not be executed if program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).

The try-catch-finally structure(Syntax):

try {

// Code block }

catch (ExceptionType1 e1) {

// Handle ExceptionType1 exceptions }

catch (ExceptionType2 e2)

{ // Handle ExceptionType2 exceptions } // ...

finally {

// Code always executed after the

// try and any catch block }

Rules for try, catch and finally Blocks:

1) Statements that might generate an exception are placed in a try block.

2) Not all statements in the try block will execute; the execution is interrupted if an exception
occurs

3) For each try block there can be zero or more catch blocks, but only one finally block.
4) The try block is followed by

i. one or more catch blocks

ii. or, if a try block has no catch block, then it must have the finally block

5) A try block must be followed by either at least one catch block or one finally block.

6) A catch block specifies the type of exception it can catch. It contains the code known as
exception handler 7) The catch blocks and finally block must always appear in conjunction
with a try block.

8) The order of exception handlers in the catch block must be from the most specific
exception

Program without Exception handling: (Default exception handler):

class Simple { public static void main(String args[]) {

int data=50/0;

System.out.println("rest of the code..."); } }

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero As displayed in the above


example, rest of the code is not executed i.e. rest of the code... statement is not printed.

Program Explanation:

The JVM firstly checks whether the exception is handled or not. If exception is not handled,
JVM provides a default exception handler that performs the following tasks:

∙ Prints out exception description.

∙ Prints the stack trace (Hierarchy of methods where the exception occurred).

∙ Causes the program to terminate.


Example:

public class Demo {

public static void main(String args[]) {

try { int data=25/0;

System.out.println(data);

} catch(ArithmeticException e)

{ System.out.println(e); }

finally {

System.out.println("finally block is always executed"); }

System.out.println("rest of the code..."); } }

Output: java.lang.ArithmeticException: / by zero

finally block is always executed

rest of the code...


Types of Exceptions

Built-in Exceptions

Built-in exceptions are the exceptions which are available in Java libraries. These exceptions
are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.
Checked Exceptions:

⎫ Checked exceptions are called compile-time exceptions because these exceptions are
checked at compile-time by the compiler.

⎫ Checked Exceptions forces programmers to deal with the exception that may be thrown.

⎫ The compiler ensures whether the programmer handles the exception using try.. catch ()
block or not. The programmer should have to handle the exception; otherwise, compilation
will fail and error will be thrown.

EXAMPLE:
1.​ ClassNotFoundException
2.​ CloneNotSupportedException
3.​ IllegalAccessException,
4.​ MalformedURLException.
5.​ NoSuchFileException
6.​ NoSuchMethodException
7.​ IOException
8.​ NoSuchFileException
9.​ NoSuchMethodException
10.​IOException

EXAMPLE PROGRAM: (CHECKED EXCEPTION)

FileNotFoundException is a checked exception in Java. Anytime, we want to read a file


from filesystem, Java forces us to handle error situation where file may not be present in
place.
Without try-catch
import java.io.*;

public class CheckedExceptionExample {


public static void main(String[] args)
{
FileReader file = new FileReader("src/somefile.txt");
}
}

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled


exception type FileNotFoundException

To make program able to compile, you must handle this error situation in
Below given code will compile absolutely fine.

With try-catch
import java.io.*;
public class CheckedExceptionExample { public
static void main(String[] args) { try {
@SuppressWarnings("resource")
FileReader file = new FileReader("src/somefile.java"); System.out.println(file.toString());}
catch(FileNotFoundException e){ System.out.println("Sorry...Requested resource not
availabe...");
}}
}
Output:

Sorry...Requested resource not availabe...

UNCHECKED EXCEPTIONS(RUNTIMEEXCEPTION):
Consider​ the​ following​ Java​​ program.​​ It​ compiles​ ​fine,​ ​but​ it
throws ArithmeticException when​run.​ The​ compiler​ allows​ it​ to​ compile,
because ArithmeticException is an unchecked exception.

class Main {
public static void main(String args[]) { int x
= 0;
int y = 10; int
z = y/x;
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero at


Main.main(Main.java:5)

✔​ The unchecked exceptions are just opposite to the checked exceptions.


✔​ Unchecked exceptions are not checked at compile-time rather they
are checked at runtime.
✔​ The compiler doesn’t force the programmers to either catch the
exception or declare it in a

✔​ The compiler doesn’t force the programmers to either catch the


exception or declare it in a throws clause.
✔​ In fact, the programmers may not even know that the exception
could be thrown.

EXAMPLE:

1.​ ArrayIndexOutOfBoundsException
2.​ ArithmeticException
3.​ NullPointerException.

EXAMPLE: UNCHECKED EXCEPTION


EXAMPLE 1: NULLPOINTER EXCEPTION
//Java program to demonstrate NullPointerException
class NullPointer_Demo

public static void main(String args[])

{try {

String a = null; //null value


System.out.println(a.charAt(0
));
} catch(NullPointerException e)
{
System.out.println("NullPoint
erException..");
}

OUTPUT:
NullPointerException..

EXAMPLE 2: NUMBERFORMAT EXCEPTION


// Java program to demonstrate NumberFormatException
class NumberFormat_Demo

public static void main(String args[])

TRY {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;
System.out.println(num);

} catch(NumberFormatException e) {
System.out.println("Number format
exception");
}

OUTPUT:

Number format exception

USER-DEFINED EXCEPTIONS (CUSTOM EXCEPTIONS)

Exception types created by the user to describe the exceptions related to their applications
are known as User-defined Exceptions or Custom Exceptions.

To create User-defined Exceptions:


1.​ Pick a self-describing *Exception class name.
2.​ Decide if the exception should be checked or unchecked.
✔​ Checked : extends Exception
✔​ Unchecked: extends RuntimeException
3.​ Define constructor(s) that call into super class constructor(s), taking
message that can be displayed when the exception is raised.

4 Write the code that might generate the defined exception inside the
try-catch block.
5.If the exception of user-defined type is generated, handle it using throw
clause
as follows:
THROW EXCEPTIONCLASSOBJECT;
Example:

The following program illustrates how user-defined exceptions can be created and
thrown.
public class EvenNoException extends Exception

EvenNoException(String str)
{

super(str); // used to refer the superclass constructor


}

public static void main(String[] args)

int arr[]={2,3,4,5};
int rem;

int i;

for(i=0;i<arr.length;i++)
{

rem=arr[i]%2;
TRY

if(rem==0)
{

System.out.println(arr[i]+" is an Even Number");


}
ELSE

EvenNoException exp=new EvenNoException(arr[i]+" is not


an Even Number");
throw exp;

catch(EvenNoException exp)
{

System.out.println("Exception thrown is "+exp);


}

} // for loop
} // main()
} // class
Output:

2​ is an Even Number
Exception thrown is EvenNoException: 3 is not an
Even Number 4 is an Even Number

Exception thrown is EvenNoException: 5 is not an Even Number

Program Explanation:

In the above program, the EvenNumberException class is created which inherits the
Exception super class. Then the constructor is defined with the call to the super class
constructor. Next, an array arr is created with four integer values. In the main(), the array
elements are checked one by one for even number. If the number is odd, then the object of
EvenNumberException class is created and thrown using throw clause. The
EvenNumberException is handled in the catch block.
Basis
final finally finalize
for
compari
son
Basic Final is a "Keyword" and Finally is a "block" in Finalize is a "method" in
"access modifier" in Java. Java. Java.
Applicabl Final is a keyword applicable to Finally is a block that is finalize() is a method
e classes, variables and methods. always associated with applicable to objects.
try and catch block.
Working (1)​ Final variable becomes A "finally" block, clean Finalize method performs
constant, and it can't be up the resources used in cleans up activities related
reassigned. "try" block. to the object before its
(2)​ A final method can't be destruction.
overridden by the child class.
(3)​ Final Class can not be
extended.
Execution Final method is executed upon "Finally" block executes finalize() method executes
its call. just after the execution just before the destruction
of"try- catch" block. of the object.
Example class FinalExample{ public class FinallyExample{ class FinalizeExample{
static void main(String[] args){ public static void public void
final int x=100; main(String[] args){ try{ finalize(){System.out.pr
x=200;//Compile Time Error int x=300; intln("finalize called");}
}} }catch(Exception public static void
e){System.out.println main(String[] args){
(e);} FinalizeExample f1=new
finally{ FinalizeExample();
System.out.println("fi FinalizeExample f2=new
nally block is executed"); FinalizeExample(); f1=null;
} f2=null; System.gc();
}} }}

Definition: Thread

A thread is a lightweight sub-process that defines a separate path of execution. It is the


smallest unit of processing that can run concurrently with the other parts (other threads) of
the same process.

✔​ Threads are independent.


✔​ If there occurs exception in one thread, it doesn't affect other threads.
✔​ It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process.

As
There is context-switching between the threads.
There can be multiple processes inside the OS, and one process can have multiple
threads.

DIFFERENCE BETWEEN THREAD AND PROCESS:

S.NO PROCESS THREAD


1) Process is a heavy weight program Thread is a light weight process
2) Each process has a complete set of its Threads share the same data
own variables
3) Processes​ must​ use​ IPC​ (Inter- Threads​ can​ directly​ communicate
Process​ Communication)​ to with each other with the help of shared
communicate with sibling processes variables

4) Cost​ of​ communication​ between Cost​ of​ communication​ between


processes is high. threads is low.
5) Process switching uses interface in Thread switching does not require
operating system. calling an operating system.
6) Processes are independent of one Threads are dependent of one another
Another
7) Each process has its own memory and All threads of a particular process shares​
resources the​ common​ memory​
and
resources
8) Creating​ &​ destroying Takes less overhead to create and
​ processes destroy individual threads
takes more overhead

3.6.1​ MULTITHREADING
A program can be divided into a number of small processes. Each small process can
be addressed as a single thread.

ADVANTAGES OF THREADS / MULTITHREADING:


1.​ Threads are light weight compared to processes.
2.​ Threads share the same address space and therefore can share both data and
code.
3.​ Context switching between threads is usually less expensive that
between processes.
4.​ Cost of thread communication is low than inter-process communication.
5.​ Threads allow different tasks to be performed concurrently.
6.​ Reduces the computation time.
7.​ Through multithreading, efficient utilization of system resources can be
achieved.
Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


maximize the utilization of CPU.

Multitasking can be achieved in two ways:


1)​ PROCESS-BASED MULTITASKING (MULTIPROCESSING):-
❖​ It is a feature of executing two or more programs concurrently.

Characteristics Multithreading Multitasking


Meaning A process is divided into several The execution of more than one task
different sub-processes called as simultaneously is called as
threads, which has its own path of multitasking.
execution. This concept is
called as multithreading.

Number of CPU Can be one or more than one One


Number of Various components of the same One by one job is being executed at
process being process are being executed at a time. a time.
executed

Number of users Usually one. More than one.


Memory Space Threads are lighter weight. They Processes are heavyweight
share the same address space tasks that require their own separate
address spaces.

Communication Interthread communication is Interprocess communication is


between units Inexpensive expensive and limited.
Context Switching Context switching from one thread to Context switching from one process
the next is lower in to another is also costly.
cost.
For example, process-based multitasking enables you to run the Java compiler at the
same time that you are using a text editor or visiting a web site.

THREAD-BASED MULTITASKING (MULTITHREADING):-


It is a feature that a single program can perform two or more tasks
simultaneously.
For instance, a text editor can format text at the same time that it is printing, as long
as these two actions are being performed by two separate threads.
Thread Model / Thread Life Cycle (Different states of a Thread)

Different states, a thread (or applet/servlet) travels from its object creation to object
removal (garbage collection) is known as life cycle of thread. A thread goes through
various stages in its life cycle. At any time, a thread always exists in any one of the following
state:
1​ New State
2​ Runnable State
3​ Running State
4​ Waiting/Timed Waiting/Blocked state
5​ Terminated State/ dead state

A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread by calling start() method, which places the thread in the
runnable state.
✔​ A new thread is also referred to as a born thread.
✔​ When the thread is in this state, only start() and stop() methods can
be called. Calling any other methods causes an
IllegalThreadStateException.
✔​ Sample Code: Thread myThread=new Thread();
2.​ RUNNABLE STATE:
After a newly born thread is started, the thread becomes runnable or running by
calling the run() method.
A thread in this state is considered to be executing its task.
Sample code: myThread.start();
The start() method creates the system resources necessary to run the thread,
schedules the thread to run and calls the thread’s run() method.

3.​ RUNNING STATE:


Thread scheduler selects thread to go from runnable to running state. In running
state Thread starts executing by entering run() method.
Thread scheduler selects thread from the runnable pool on basis of priority, if priority
of two threads is same, threads are scheduled in unpredictable manner. Thread
scheduler behaviour is completely unpredictable.
When threads are in running state, yield() method can make thread to go in Runnable
state.

4.​ WAITING/TIMED WAITING/BLOCKED STATE :


❖​ Waiting State:
Sometimes one thread has to undergo in waiting state because another thread starts
executing. A runnable thread can be moved to a waiting state by calling the wait()
method.
A thread transitions back to the runnable state only when another thread signals the
waiting thread to continue executing.
A call to notify() and notifyAll() may bring the thread from waiting state to runnable
state.
❖​ TIMED WAITING:
A runnable thread can enter the timed waiting state for a specified interval of time
by calling the sleep() method.
After the interval gets over, the thread in waiting state enters into the runnable state.
Sample Code:
TRY {

Thread.sleep(3*60*1000);// thread sleeps for 3 minutes

CATCH(INTERRUPTEDEXCEPTION EX) {}
❖​ Blocked State:
When a particular thread issues an I/O request, then operating system moves the
thread to blocked state until the I/O operations gets completed.
✔​ This can be achieved by calling suspend() method.
✔​ After the I/O completion, the thread is sent back to the runnable state.
5.​ TERMINATED STATE:
A RUNNABLE THREAD ENTERS THE TERMINATED STATE WHEN,
(i)​ It completes its task (when the run() method has finished)
PUBLIC VOID RUN() { }

(ii)​ Terminates ( when the stop() is invoked) – myThread.stop();


(iii)​ A terminated thread cannot run again.
THE “MAIN” THREAD
The “main” thread is a thread that begins running immediately when a java program starts up.
The “main” thread is important for two reasons:
It is the thread form which other child threads will be spawned.
It must be the last thread to finish execution because it performs various shutdown
actions.
Although the main thread is created automatically when our program is started, it can
be controlled through a Thread object.
To do so, we must obtain a reference to it by calling the method currentThread().
EXAMPLE:
class CurrentThreadDemo {
public static void main(String args[])
{

Thread t=Thread.currentThread(); System.out.println(“CurrentThread: “+t);

// change the name of the main thread


t.setName(“My Thread”);
System.out.println(“After name change : “+t);
try {
for(int n=5;n>0;n--) {
System.out.println(n);
Thread.sleep(1000);//
delay for 1 second
}

} catch(InterruptedException e) {
System.out.println(“Main Thread Interrrupted”);
}

Output:

Current Thread: Thread[main,5,main]


After name change: Thread[My Thread,5,main]
5
4
3
2
1

Creating Threads
We can create threads by instantiating an object of type Thread. Java defines two
ways to create threads:
1.​By implementing Runnable interface (java.lang.Runnable)
2.​By extending the Thread class (java.lang.Thread)

1.​CREATING THREADS BY IMPLEMENTING RUNNABLE INTERFACE:


●​ The Runnable interface should be implemented by any class whose
instances are intended to be executed as a thread.
●​ Implementing thread program using Runnable is preferable than
implementing it by extending Thread class because of the following
two reasons:
1.​ If a class extends a Thread class, then it cannot extend any other
class.
2.​ If a class Thread is extended, then all its functionalities get
inherited. This is an expensive operation.
●​ The Runnable interface has only one method that must be
overridden by the class which implements this interface:
PUBLIC VOID RUN()// RUN() CONTAINS THE LOGIC OF THE THREAD

// IMPLEMENTATION CODE
}

●​ STEPS FOR THREAD CREATION:


1.​ Create a class that implements Runnable interface. An object of this
class is
Runnable object.

public class MyThread implements Runnable


{
---

2.​Override the run() method to define the code executed by the thread.
3.​Create an object of type Thread by passing a Runnable object as
argument.
THREAD T=NEW THREAD(RUNNABLE THREADOBJ, STRING THREADNAME);
4.​Invoke the start() method on the instance of the Thread class.
T.START();

●​ Example:
class MyThread implements Runnable

public void run()

for(int i=0;i<3;i++)

System.out.println(Thread.currentThread().getName()+" # Printing "+i);

try

Thread.sleep(1000);

}catch(InterruptedException e)
{

System.out.println(e);
}

public class RunnableDemo {

public static void main(String[] args)

MyThread obj=new MyThread();


MyThread obj1=new MyThread();
Thread t=new
Thread(obj,"Thread-1"); t.start();
Thread t1=new Thread(obj1,"Thread-2");
t1.start();
}

}
OUTPUT:
Thread-0 # Printing 0 Thread-1 # Printing 0 Thread-1 # Printing 1 Thread-0 # Printing 1
Thread-0 # Printing 2 Thread-1 # Printing 2

2.​ CREATING THREADS BY EXTENDING THREAD CLASS:


Thread class provide constructors and methods to create and perform operations on a
thread.
COMMONLY USED CONSTRUCTORS OF THREAD CLASS:
●​ Thread()
●​ Thread(String name)
●​ Thread(Runnable r)
●​ Thread(Runnable r, String name)
All the above constructors creates a new thread.

COMMONLY USED METHODS OF THREAD CLASS:


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

●​ STEPS FOR THREAD CREATION:


1.​ Create a class that extends
java.lang.Thread class. public
class MyThread extends Thread
{

---

2.​ Override the run() method in the sub class to define the code
executed by the thread.
3.​Create an object of this sub class.
MYTHREAD T=NEW MYTHREAD(STRING THREADNAME);
4.​ Invoke the start() method on the instance of the subclass to
make the thread for running.
START();

●​ Example:
class SampleThread extends Thread

{
public void run()
{
for(int i=0;i<3;i++)
{
System.out.println(Thread.currentThread().getName()+" # Printing "+i);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{

System.out.println(e);
}
}
}
}

public class ThreadDemo {

public static void main(String[] args) {


SampleThread obj=new SampleThread();
obj.start();

SampleThread obj1=new SampleThread();


obj1.start();
}

OUTPUT

Thread-0 # Printing 0

Thread-1 # Printing 0

Thread-1 # Printing 1

Thread-0 # Printing 1

Thread-0 # Printing 2

Thread-1 # Printing 2

THREAD PRIORITY
✔​ Thread priority determines how a thread should be treated with
respect to others.
✔​ Every thread in java has some priority, it may be default priority
generated by JVM or customized priority provided by programmer.
✔​ Priorities are represented by a number between 1 and 10.
1 – Minimum Priority5 – Normal Priority 10 – Maximum Priority
✔​ Thread scheduler will use priorities while allocating processor. The
thread which is having highest priority will get the chance first.
✔​ Higher priority threads get more CPU time than lower priority threads.
✔​ A higher priority thread can also preempt a lower priority thread.
For instance, when a lower priority thread is running and a higher
priority thread resumes (for sleeping or waiting on I/O), it will
preempt the lower priority thread.
✔​ If two or more threads have same priorities, we can’t predict the
execution of waiting threads. It is completely decided by thread
scheduler. It depends on the type of algorithm used by thread

scheduler.
✔​ 3 CONSTANTS DEFINED IN THREAD CLASS:

1.​public static int MIN_PRIORITY


2.​public static int NORM_PRIORITY
3.​public static int MAX_PRIORITY
✔​ Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1
and the value of MAX_PRIORITY is 10.
✔​ To set a thread’s priority, use the setPriority() method.
✔​ To obtain the current priority of a thread, use getPriority() method.

✔​ Example:
class TestMultiPriority1 extends Thread{ public void
run(){
System.out.println("running thread name is:"+Thread.currentThread().getNam e());
System.out.println("running thread priority is:"+
Thread.currentThread().getPriority());

public static void main(String args[]){


TestMultiPriority1m1=new TestMultiPriority1();
TestMultiPriority1m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY); m1.start();
m2.start();
}

OUTPUT:

running thread name


is:Thread-0 running thread
priority is:10 running thread
name is:Thread-1 running
thread priority is:1

Thread Synchronization
Definition: Thread Synchronization

Thread synchronization is the concurrent execution of two or more threads that share
critical resources.

When two or more threads need to use a shared resource, they need some way to ensure
that the resource will be used by only one thread at a time. The process of ensuring single
thread access to a shared resource at a time is called synchronization.

Threads should be synchronized to avoid critical resource use conflicts.


Otherwise, conflicts may arise when parallel-running threads attempt to
modify a common variable at the same time.
✔​ WHY USE SYNCHRONIZATION
The synchronization is mainly used to
1.​ To prevent thread interference.
2.​ To prevent consistency problem.

✔​ THREAD SYNCHRONIZATION
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1.​ Mutual Exclusive
1.​ Synchronized method.
2.​ Synchronized block.
3.​ static synchronization.
2.​ Cooperation (Inter-thread communication in java)

✔​ MUTUAL EXCLUSIVE
Mutual Exclusive helps keep threads from interfering with one another
while sharing data. This can be done by two ways in java:
1.​ by synchronized method
2.​ by synchronized block

✔​ CONCEPT OF LOCK IN JAVA


Synchronization is built around an internal entity known as the lock or
monitor. Every object has a lock associated with it. By convention, a thread
that needs consistent access to an object's fields has to acquire the object's
lock before accessing them, and then release the lock when it's done with
them.
1.​ JAVA SYNCHRONIZED METHOD

✔​ If you declare any method as synchronized, it is known as synchronized


method. Synchronized method is used to lock an object for any shared
resource.
✔​ When a thread invokes a synchronized method, it automatically
acquires the lock for that object and releases it when the thread
completes its task.

Syntax to use synchronized method:


ACCESS_MODIFIER SYNCHRONIZED RETURN_TYPE METHOD_NAME(PARAMETERS)
{ …….. }

Example of java synchronized method:

class Table{
SYNCHRONIZED VOID PRINTTABLE(INT N)//SYNCHRONIZED METHOD

FOR(INT
I=1;I<=5
;I++) {
SYSTEM.
OUT.PRIN
TLN(N*I);
TRY{​
THREAD.
SLEEP(40
0);​ }
catch(Exception e) { System.out.println(e); }

class MyThread1
extends Thread {
Table t;
MyT
hread
1(Tab
le t){
this.t
=t;
}

public void
run(){
t.printTabl
e(5);
}

class MyThread2
extends Thread{
Table t;
MyT
hread
2(Tab
le t){
this.t
=t;
}

public void
run(){
t.printTabl
e(100);
}

public class
TestSynchronizati
on2{ public static
void main(String
args[]){
Table obj = new Table();

//only one object
MyThread1 t1=new
MyThread1(obj);
MyThread2 t2=new
MyThread2(obj);
t1.start();
t2.start();
}}

OUTPUT:
5
10
15
20
25
100
200
300
400
500
2.​SYNCHRONIZED BLOCK IN JAVA
✔​ Synchronized block can be used to perform synchronization on any
specific resource of the method.
✔​ Suppose you have 50 lines of code in your method, but you want to
synchronize only 5 lines, you can use synchronized block.
✔​ If you put all the codes of the method in the synchronized block, it
will work same as the synchronized method.

POINTS TO REMEMBER FOR SYNCHRONIZED BLOCK


●​ Synchronized block is used to lock an object for any shared resource.
●​ Scope of synchronized block is smaller than the method.

Syntax to use synchronized block

1.​ synchronized (object reference expression) {


2.​ //code block
3. }

Example of synchronized block

class Table{
void printTable(int n)
{

synchronized(this) //synchronized block


{

for(int
i=1;i<=5;i++)
{
System.out.pri
ntln(n*i);
try{​ Thread.sleep(400);​ }catch(Exception
e){System.out.println(e);}
}

}//end of the method


}

class MyThread1
extends
Thread{
Table t;
MyThread1(Table t){
this.t=t;
}

public void run(){


t.printTable(5);
}

class MyThread2
extends
Thread{
Table t;
MyThread2(Table t){
this.t=t;
}

public void run(){


t.printTable(100);
}

public class TestSynchronizedBlock1


{

public static void main(String args[])


{
Table obj = new
Table();//only one
object MyThread1
t1=new
MyThread1(obj);
MyThread2 t2=new
MyThread2(obj);

t1.start();
t2.start();
}

OUTPUT:
5
10
15
20
25
100
200
300
400
500

DIFFERENCE BETWEEN SYNCHRONIZED METHOD AND SYNCHRONIZED BLOCK:

Synchronized method Synchronized block


1.​ Lock is acquired on critical block of
1.​ Lock is acquired on whole method.
code only.
2.​ Less preferred.
2.​ Preferred.
3.​ Performance will be less as compared to
synchronized block. 3.​ Performance will be better as compared
to synchronized method.

: Inter-Thread Communication
Inter-Thread Communication or Co-operation is all about allowing
synchronized threads to communicate with each other.
It is implemented by following methods of Object class and all these
methods can be called only from within a synchronized context.

S.No. Method & Description


1 public final void wait() throws InterruptedException
Causes the current thread to wait until another thread invokes the notify().
2 public final void wait(long timeout) throws InterruptedException
Causes current thread to wait until either another thread invokes the notify() method or the
notifyAll() method for this object, or a specified amount of time has elapsed.
Parameters:
timeout − the maximum time to wait in milliseconds.

3 public final void notify()


Wakes up a single thread that is waiting on this object's monitor.
4 Public final void notifyAll()
Wakes up all the threads that called wait( ) on the same object.

Difference between wait() and sleep()


Parameter wait() sleep()
wait should be called from
synchronized context i.e. from block
or method, If you do not call it using It need not be called from
Synchonized synchronized context,​ it​ synchronized block or methods
will throw IllegalMonitorStateExcept
ion

Sleep method operates on current


wait method operates on Object and
Calls on thread and is in java.lang.Thread
defined in Object class

wait release lock of object on which it


Sleep method does not release lock
Release of lock is called and also other locks if it
at all
holds any
Wake up until call notify() or notifyAll() from Until time expires​ or calls
condition Object class interrupt()
static wait is non-static method sleep is static method

Example: The following program illustrates simple bank transaction


operations with inter-thread communication:
class Customer{

int Balance=10000;

synchronized void withdraw(int amount)

System.out.println("going to withdraw..."+amount);

if(Balance<amount)
{

System.out.println("Less balance; Balance = Rs.


"+Balance+"\nWaiting for deposit...\n");
TRY

wait();
}

catch(Exception e){}

Balance-=amount;
System.out.println("withdr
aw completed...");
}

synchronized void deposit(int amount)

System.out.println("going to
deposit... Rs. "+amount);
Balance+=amount;
System.out.println("deposit completed... Balance
= "+Balance); notify();
}

class ThreadCommn

{
public static void
main(String
args[]) {
Customer
c=new
Customer();
new
Thread()

public void run(){c.withdraw(20000);}

}.start();
new Thread(){

public void run(){c.deposit(15000);}

}.start();
}

OUTPUT:

going to withdraw...20000
Less balance; Balance = Rs.
10000 Waiting for deposit...
going to deposit... Rs. 15000
deposit completed... Balance =
25000 withdraw completed...

WRAPPERS
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.

THE TABLE BELOW SHOWS THE PRIMITIVE TYPE AND THE EQUIVALENT WRAPPER CLASS:
Primitive Data Type Wrapper Class
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double
Boolean Boolean
Char Character

Use of Wrapper classes


​ Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primitive value in
an object, it will change the original value.
​ Serialization: We need to convert the objects into streams to perform the serialization.
If we have a primitive value, we can convert it in objects through the wrapper classes.
​ Synchronization: Java synchronization works with objects in Multithreading.
​ java.util package: The java.util package provides the utility classes to deal with
objects.
​ Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet,
TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

Example:
//Java Program to convert all primitives into its corresponding
//wrapper objects and vice-versa public class Wrapper

Example3{ public static void main(String args[]){ byte b=10;

short s=20; int i=30; long l=40;


float f=50.0F; double d=60.0D; char c='a'; boolean b2=true;

//Autoboxing: Converting primitives into objects Byte byteobj=b;


Short shortobj=s; Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;
//Printing objects
System.out.println("---Printing object
values---"); System.out.println("Byte object:
"+byteobj); System.out.println("Short object:
"+shortobj); System.out.println("Integer
object: "+intobj); System.out.println("Long
object: "+longobj); System.out.println("Float
object: "+floatobj);
System.out.println("Double object:
"+doubleobj); System.out.println("Character
object: "+charobj);
System.out.println("Boolean object:
"+boolobj);
//Unboxing: Converting Objects to
Primitives byte bytevalue=byteobj;
Short
shortvalue=sh
ortobj; int
intvalue=intob
j;
long
longvalue=l
ongobj;
float
floatvalue=
floatobj;
double
doublevalue=doubl
eobj; char
charvalue=charobj;
boolean
boolvalue=boolobj;
//Printing primitives
System.out.println("---Printing primitive
values---"); System.out.println("byte value:
"+bytevalue); System.out.println("short value:
"+shortvalue); System.out.println("int value:
"+intvalue); System.out.println("long value:
"+longvalue); System.out.println("float value:
"+floatvalue); System.out.println("double
value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value:
"+boolvalue);
}

OUTPUT
---Printing
object
values---
Byte
object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double
object:
60.0
Character
object: a
Boolean
object: true
---Printing primitive
values--- byte value:
10
short value: 20
int value: 30
long value: 40
float value: 50.0
double
value:
60.0
char
value:
a
boole
n
value:
true

3.14.​ AUTOBOXING
The automatic conversion of primitive data type into its corresponding
wrapper class is known as autoboxing, for example, byte to Byte, char to
Character, int to Integer, long to Long, float to Float, boolean to Boolean,
double to Double, and short to Short.

EXAMPLE:
public class
WrapperExample
1{ public static
void main(String
args[]){
//Convert
ing int
into
Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}

OUTPUT
20 20 20

3.14.1.​ UNBOXING
The automatic conversion of wrapper type into its corresponding primitive
type is known as unboxing. It is the reverse process of autoboxing.
EXAMPLE:

//Unboxing example
of Integer to int
public class
WrapperExample2
{

public static void main(String args[])


{

//Convertin
g Integer to
int Integer
a=new
Integer(3);
int i=a.intValue();​ //converting Integer to int explicitly
int j=a;​ //unboxing, now compiler will write
a.intValue() internally System.out.println(a+" "+i+" "+j);
}

OUTPUT
3​ 3 3
UNIT - V GUI PROGRAMMING WITH SWING
Introduction
Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to
create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

limitations of AWT, MVC architecture

Limitations of AWT:

The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but
limited graphical interface. One reason for the limited nature of the AWT is that it translates its
various visual components into their corresponding, platform- specific equivalents or peers. This
means that the look and feel of a component is defined by the platform, not by java. Because the
AWT components use native code resources, they are referred to as heavy weight. The use of
native peers led to several problems. First, because of variations between operating systems, a
component might look, or even act, differently on different platforms. This variability threatened
java’s philosophy: write once, run anywhere. Second, the look and feel of each component was
fixed and could not be changed. Third, the use of heavyweight components caused some
frustrating restrictions. Due to these limitations Swing came and was integrated to java. Swing is
built on the AWT. Two key Swing features are: Swing components are light weight, Swing
supports a pluggable look and feel.

The MVC Connection:

In general, a visual component is a composite of three distinct aspects:

●​The way that the component looks when rendered on the screen

●​The way that the component reacts to the user

●​The state information associated with the component.

The Model-View-Controller architecture is successful for all these. Components and

Containers:

A component is an independent visual control, such as a push button. A container holds a group of
components. Furthermore in order for a component to be displayed it must be held with in a
container. Swing components are derived from JComponent class. Note that all component classes
begin with the letter J. For example a label is JLabel, a button is JButton etc. Swing defines two
types of containers. The first are top level containers: JFrame, JApplet, JWindow, and JDialog.
These containers do not inherit JComponent. They do, however inherit the AWT classes Container
and Component. Unlike Swing’s other components which are heavy weight, the top level containers
are heavy weight. The second type of containers are light weight inherit from JComponent.
Example- Jpanel.
Java Layout Managers

The Layout Managers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent the layout managers:

1.​ java.awt.BorderLayout

2.​ java.awt.FlowLayout

3.​ java.awt.GridLayout

4.​ java.awt.CardLayout

5.​ java.awt.GridBagLayout

6.​ javax.swing.BoxLayout

7.​ javax.swing.GroupLayout

8.​ javax.swing.ScrollPaneLayout

9.​ javax.swing.SpringLayout etc.


Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west, and
center. Each region (area) may contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:

1.​ public static final int NORTH

2.​ public static final int SOUTH

3.​ public static final int EAST

4.​ public static final int WEST

5.​ public static final int CENTER


Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the components.
BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor
FileName: Border.java

import java.awt.*;

import javax.swing.*;

public class Border

{ JFrame;

Border()

f = new JFrame();

// creating buttons

JButton b1 = new JButton("NORTH");; // the button will be labeled


as NORTH

JButton b2 = new JButton("SOUTH");; // the button will be labeled


as SOUTH

JButton b3 = new JButton("EAST");; // the button will be labeled as


EAST

JButton b4 = new JButton("WEST");; // the button will be labeled as


WEST

JButton b5 = new JButton("CENTER");; // the button will be labeled


as CENTER
f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North
Direction
f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South
Direction
f.add(b3, BorderLayout.EAST); // b2 will be placed in the East
Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West
Direction
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center

fsetSize(300,300);
f.setVisible(true);
}

public static void main(String[] args) {

new Border();

OUTPUT:
Example of BorderLayout class: Using BorderLayout(int hgap, int vgap) constructor

The following example inserts horizontal and vertical gaps between buttons
using the parameterized constructor BorderLayout(int hgap, int gap)

FileName: BorderLayoutExample.java

// import statement import java.awt.*; import javax.swing.*;

public class BorderLayoutExample

JFrame jframe;

// constructor
BorderLayoutExample()
{// creating a aFrame jframe = new JFrame();

// create buttons JButton btn1 = new JButton("NORTH"); JButton btn2 = new


JButton("SOUTH"); JButton btn3 = new JButton("EAST"); JButton btn4 = new
JButton("WES");
JButton btn5 = new JButton("CENTER");
// creating an object of the BorderLayout class using
// the parameterized constructor where the horizontal gap is 20
// and vertical gap is 15. The gap will be evident when buttons are placed
// in the frame
jframe.setLayout(new BorderLayout(20, 15)); jframe.add(btn1, BorderLayout.NORTH);
jframe.add(btn2, BorderLayout.SOUTH); jframe.add(btn3, BorderLayout.EAST);
jframe.add(btn4, BorderLayout.WEST); jframe.add(btn5, BorderLayout.CENTER);
jframe.setSize(300,300);

jframe.setVisible(true);}

// main method
public static void main(String argvs[]) {new BorderLayoutExample(); } }

Output:

Java BorderLayout: Without Specifying Region

The add() method of the JFrame class can work even when we do not specify the region. In
such a case, only the latest component added is shown in the frame, and all the components
added previously get discarded. The latest component covers the whole area. The following
example shows the same.

FileName: BorderLayoutWithoutRegionExample.java

//import statements import


java.awt.*; import
javax.swing.*;
public class BorderLayoutWithoutRegionExample {
JFrame jframe;

//constructor
BorderLayoutWithoutRegionExample(){

jframe = new JFrame();


JButton btn1 = new JButton("NORTH");
JButton btn2 = new
JButton("SOUTH");
JButton btn3 = new JButton("EAST");
JButton btn4 = new JButton("WEST");
JButton btn5 = new JButton("CENTER");
// horizontal gap is 7, and the vertical gap is 7
// Since region is not specified, the gaps are of no use
jframe.setLayout(new BorderLayout(7, 7));
// each button covers the whole area
// however, the btn5 is the latest button
// that is added to the frame; therefore, btn5
// is shown jframe.add(btn1);
jframe.add(btn2);
jframe.add(btn3);
jframe.add(btn4);
jframe.add(btn5);

jframe.setSize(300,300);
jframe.setVisible(true);
}// main method

public static void main(String argvs[])

{new BorderLayoutWithoutRegionExample();

}}

Output:

Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular
grid. One component is displayed in each rectangle.

Constructors of GridLayout class

GridLayout(): creates a grid layout with one column per component in a row.

GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no
gaps between the components.

GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given
rows and columns along with given horizontal and vertical gaps.

Example of GridLayout class: Using GridLayout() Constructor

The GridLayout() constructor creates only one row. The following example shows the usage of
the parameterless constructor.

FileName: GridLayoutExample.java​

// import statements
import java.awt.*;
import javax.swing.*;

Public class
GridLayoutExample

{JFrame frameObj;// constructor GridLayoutExample()

frameObj = new JFrame();// creating 9 buttons


JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
JButton btn3 = new JButton("3");
JButton btn4 = new JButton("4");
JButton btn5 = new JButton("5");
JButton btn6 = new JButton("6");
JButton btn7 = new JButton("7");
JButton btn8 = new JButton("8");
JButton btn9 = new JButton("9");
// adding buttons to the frame
// since, we are using the parameterless constructor, therfore;
// the number of columns is equal to the number of buttons we
// are adding to the frame. The row count remains one.
frameObj.add(btn1); frameObj.add(btn2);
frameObj.add(btn3); frameObj.add(btn4);
frameObj.add(btn5); frameObj.add(btn6);
frameObj.add(btn7); frameObj.add(btn8);
frameObj.add(btn9);
// setting the grid layout using the parameterless
constructor frameObj.setLayout(new GridLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}// main method

public static void main(String argvs[])

{new GridLayoutExample();}

Output:
Java FlowLayout

The Java FlowLayout class is used to arrange the components in a line, one
after another (in a flow). It is the default layout of the applet or panel.
\ields of FlowLayout class

1.​ public static final int LEFT


2.​ public static final int RIGHT

3.​ public static final int CENTER

4.​ public static final int LEADING

5.​ public static final int TRAILING


Constructors of FlowLayout class
FlowLayout(): creates a flow layout with centered alignment and a default 5
unit horizontal and vertical gap.

FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.

FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor

FileName: FlowLayoutExample.java

// import statements
import java.awt.*;
import javax.swing.*;

public class FlowLayoutExample

JFrame frameObj;

//constructor
FlowLayoutExample()

// creating a frame object


frameObj = new
JFrame();
// creating the buttons
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
JButton b10 = new JButton("10");
// adding the buttons to frame
frameObj.add(b1); frameObj.add(b2); frameObj.add(b3);
frameObj.add(b4); frameObj.add(b5); frameObj.add(b6);
frameObj.add(b7); frameObj.add(8); frameObj.add(b9);
frameObj.add(b10);
// parameter less constructor is used
// therefore, alignment is center
// horizontal as well as the vertical gap is 5 units.
frameObj.setLayout(new FlowLayout());
frameObj.setSize(300, 300);
frameObj.setVisible(true);
}

// main method

public static void main(String argvs[]) new FlowLayoutExample();

Output:
Java CardLayout
The Java CardLayout class manages the components in such a manner that only one component
is visible at a time. It treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout Class
CardLayout(): creates a card layout with zero horizontal and vertical gap.

CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.

Commonly Used Methods of CardLayout Class


public void next(Container parent): is used to flip to the next card of the
given container.

public void previous(Container parent): is used to flip to the previous card


of the given container.

public void first(Container parent): is used to flip to the first card of the
given container.

public void last(Container parent): is used to flip to the last card of the
given container.

public void show(Container parent, String name): is used to flip to the


specified card with the given name.

Example of CardLayout Class: Using Default Constructor


The following program uses the next() method to move to the next card of the container.

FileName: CardLayoutExample1.java

// import statements import java.awt.*;

public class CardLayoutExample1 extends JFrame implements ActionListener


{

CardLayout crd;
// button variables to hold the references of buttons
JButton btn1, btn2, btn3;
Container cPane;
//construct or of the class
CardLayoutExample1()
{
cPane = getContentPane();

//default constructor used


// therefore, components will
// cover the whole area

crd = new CardLayout();


cPane.setLayout(crd);
// creating the buttons
btn1 = new JButton("Apple");

btn2 = new JButton("Boy");

btn3 = new JButton("Cat");


// adding listeners to it
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
cPane.add("a", btn1); // first card is
the button btn1 cPane.add("b",
btn2); // first card is the button
btn2 cPane.add("c", btn3); // first
card is the button btn3
}public void actionPerformed(ActionEvent e)

// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon
cliking crd.next(cPane);
}

// main method
public static void main(String argvs[])

// creating an object of the class CardLayoutExample1

CardLayoutExample1 crdl = new CardLayoutExample1();


// size is 300 * 300
crdl.setSize(300, 300);
crdl.setVisible(true);
crdl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

OUTPUT:

When the button named apple is clicked, we get

When the boy button is clicked, we get


Again, we reach the first card of the container if the cat button is clicked, and
the cycle continues.

Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along
their baseline.
Modifier and Type Field Description

double[] columnWeights It is used to hold the overrides to the column e


weights.

int[] columnWidths It is used to hold the overrides to e


the column minimum width.

protected comptable It is used to maintains the association between a n


Hashtable<Compone component and its gridbag constraints. g
nt,GridBagConstraint
s>
protected defaultConstrain It is used to hold a gridbag constrain instance t
GridBagConstraints ts containing the default values. s

protected layoutInfo o
GridBagLayoutInfo It is used to hold the layout information f the gridbag. r

protected static int MAXGRIDSIZE No​ longer​ in​ use​ just​ for​ backward compatibility d

protected static int MINSIZE It is smallest grid that can be laid out by the grid bag e
layout.

protected static int PREFERREDSIZ It is preferred grid size that can be laid o by the grid u
E bag layout. t

int[] rowHeights It is used to hold the overrides to the row minimum w


heights.

double[] rowWeights It is used to hold the overrides to the row weights. w


Department of CSE​ Page 19 of 63
MODIFIER AND TYPE​ METHOD​ DESCRIPTION

Void addLayoutComponent(Component It adds specified component to the


comp, Object constraints) layout, using the specified
constraints object.

Void addLayoutComponent(Stringname, It has no effect, since this layout


Component comp) manager does not use a
per-component string.

protected void adjustForGravity(GridBagConst It adjusts the x, y, width, and


raints constraints, Rectangle r) height fields to the correct
values depending on the
constraint geometry and pads.

protected void AdjustForGravity(GridBagConst This​ method​ is​ for


raints constraints, Rectangle r) backwards compatibility only

protected void arrangeGrid(Container parent) Lays out the grid.

protected void ArrangeGrid(Container parent) This method is obsolete and


supplied for backwards
compatibility

GridBagConstraints getConstraints(Component comp) It is for getting the constraints


for the specified component.

Float getLayoutAlignmentX(Container It returns the alignment along the x


parent) axis.

Float getLayoutAlignmentY(Container It returns the alignment along the y


parent) axis.

int[][] getLayoutDimensions() It determines column


widths and row heights for
the layout grid.

protected GridBagLayoutInfo getLayoutInfo(Container parent, int This method is obsolete and supplied
sizeflag) for backwards compatibility.
protected GridBag GetLayoutInfo(Container parent, int This method is obsolete and
sizeflag)
LayoutInfo supplied for backwards compatibility.

Point getLayoutOrigi() It determines the origin


of the layout area, in
the graphics coordinate
space of the target
container.
double[][] getLayoutWeights() It determines the weights of the layout
grid's columns and rows.

protected Dimension getMinSize(Containerparent, It figures out the minimum size of


GridBagLayoutInfo info) the master based on the information
from getLayoutInfo.

protected Dimension GetMinSize(Containerparent, This method is obsolete and supplied


GridBagLayoutInfo info) for backwards compatibility only
The components may not be of the same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells. Each component occupies one or more cells known as its display area. Each
component associates an instance of GridBagConstraints. With the help of the constraints object, we
arrange the component's display area on the grid. The GridBagLayout manages each component's
minimum and preferred sizes in order to determine the component's size. GridBagLayout components
are also arranged in the rectangular grid but can have many different sizes and can occupy multiple
rows or columns.

Constructor

GridBagLayout(): The parameterless constructor is used to create a grid bag layout manager.
GridBagLayout Methods

Example 1

FileName: GridBagLayoutExample.java

import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;

public class GridBagLayoutExample extends JFrame{

public static void main(String[] args) {

GridBagLayoutExample a = new GridBagLayoutExample();


}

Public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints(); setLayout(grid);
setTitle("GridBag Layout Example"); GridBagLayout layout
= new GridBagLayout();
this.setLayout(layout);
gbc.fill=GridBagConstraints.HORIZONTAL; gbc.gridx= 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);

gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);

gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);

gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);

gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300,300); setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE); } }

OUTPUT:
But, the modern approach for event processing is based on the Delegation Model. It defines a
standard and compatible mechanism to generate and process events. In this model, a source generates
an event and forwards it to one or more listeners. The listener waits until it receives an event. Once it
receives the event, it is processed by the listener and returns it. The UI elements are able to delegate
the processing of an event to a separate function.

The key advantage of the Delegation Event Model is that the application logic is completely
separated from the interface logic.In this model, the listener must be connected with a source to
receive the event notifications. Thus, the events will only be received by the listeners who wish to
receive them. So, this approach is more convenient than the inheritance-based event model (in Java
1.0).
In the older model, an event was propagated up the containment until a component was handled. This
needed components to receive events that were not processed, and it took lots of time. The
Delegation Event model overcame this issue.
Basically, an Event Model is based on the following three components:

o​ Events
Events Sources

Events

Listener Events

The Events are the objects that define state change in a source. An event can be generated as a
reaction of a user while interacting with GUI elements. Some of the event generation activities are
moving the mouse pointer, clicking on a button, pressing the keyboard key, selecting an item from
the list, and so on. We can also consider many other user operations as events.

The Events may also occur that may be not related to user interaction, such as a timer expires,
counter exceeded, system failures, or a task is completed, etc. We can define events for any of the
applied actions.

Event Sources

A source is an object that causes and generates an event. It generates an event when the internal state
of the object is changed. The sources are allowed to generate several different types of events.

A source must register a listener to receive notifications for a specific event. Each event contains its
registration method. Below is an example:
1. public void addTypeListener (TypeListener e1)

From the above syntax, the Type is the name of the event, and e1 is a reference to the event listener. For
example, for a keyboard event listener, the method will be called as addKeyListener(). For the mouse
event listener, the method will be called as addMouseMotionListener(). When an event is triggered
using the respected source, all the events will be notified to registered listeners and receive the event
object. This process is known as event multicasting. In few cases, the event notification will only be sent
to listeners that register to receive them.
Some listeners allow only one listener to register. Below is an example:

1. public void addTypeListener(TypeListener e2) throws java.util.TooManyListenersException

From the above syntax, the Type is the name of the event, and e2 is the event listener's reference.
When the specified event occurs, it will be notified to the registered listener. This process is known
as unicasting events.

A source should contain a method that unregisters a specific type of event from the listener if not
needed. Below is an example of the method that will remove the event from the listener.
1. public void removeTypeListener(TypeListener e2?)

From the above syntax, the Type is an event name, and e2 is the reference of the listener. For
example, to remove the keyboard listener, the removeKeyListener() method will be called.

The source provides the methods to add or remove listeners that generate the events. For example,
the Component class contains the methods to operate on the different types of events, such as adding
or removing them from the listener.

Event Listeners

An event listener is an object that is invoked when an event triggers. The listeners require two things;
first, it must be registered with a source; however, it can be registered with several resources to
receive notification about the events. Second, it must implement the methods to receive and process
the received notifications.

The methods that deal with the events are defined in a set of interfaces. These interfaces can be
found in the java.awt.event package.

For example, the MouseMotionListener interface provides two methods when the mouse is dragged
and moved. Any object can receive and process these events if it implements the
MouseMotionListener interface.

Types of Events

The events are categories into the following two categories:

THE FOREGROUND EVENTS:THE FOREGROUND EVENTS ARE THOSE EVENTS THAT REQUIRE DIRECT INTERACTION OF THE
USER. THESE TYPES OF EVENTS ARE GENERATED AS A RESULT OF USER INTERACTION WITH THE GUI COMPONENT. FOR
EXAMPLE, CLICKING ON A BUTTON, MOUSE MOVEMENT, PRESSING A KEYBOARD KEY, SELECTING AN OPTION FROM THE LIST,
ETC.

THE BACKGROUND EVENTS :

The Background events are those events that result from the interaction of the end-user. For example,
an Operating system interrupts system failure (Hardware or Software).

To handle these events, we need an event handling mechanism that provides control over the events
and responses.
Handling Mouse Events
Mouse events occur with mouse movements in forms and controls. Following are the various mouse
events related with a Control class −
MouseDown − it occurs when a mouse button is pressed
MouseEnter − it occurs when the mouse pointer enters the control
MouseHover − it occurs when the mouse pointer hovers over the control
MouseLeave − it occurs when the mouse pointer leaves the control
MouseMove − it occurs when the mouse pointer moves over the control
MouseUp − it occurs when the mouse pointer is over the control and the mouse buttonis released
MouseWheel − it occurs when the mouse wheel moves and the control has focus
The event handlers of the mouse events get an argument of type MouseEventArgs.
The MouseEventArgs object is used for handling mouse events. It has the following properties −
Buttons − indicates the mouse button pressed
Clicks − indicates the number of clicks
Delta − indicates the number of detents the mouse wheel rotated
X − indicates the x-coordinate of mouse click
Y − indicates the y-coordinate of mouse click
Example
Following is an example, which shows how to handle mouse events.
Take the following steps
−Add three labels, three text boxes and a button control in the form.

Change the text properties of the labels to - Customer ID, Name and Address, respectively.
Change the name properties of the text boxes to txtID, txtName and txtAddress, respectively.
Change the text property of the button to 'Submit'.
Add the following code in the code editor window − Public Class
Form1
Private Sub Form1_Load(sender As Object, e As EventArgs)
Handles MyBase.Load ' Set the caption bar text of the form.
Me.Text = "tutorialspont.com" End Sub
Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)_ Handles
txtID.MouseEnter
'code for handling mouse enter on ID textbox txtID.BackColor
= Color.CornflowerBlue txtID.ForeColor = Color.White
End Sub
Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _ Handles txtID.MouseLeave
'code for handling mouse leave on ID textbox txtID.BackColor = Color.White txtID.ForeColor =
Color.Blue
End Sub
Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _ Handles
txtName.MouseEnter
'code for handling mouse enter on Name textbox
txtName.BackColor = Color.CornflowerBlue
txtName.ForeColor = Color.White
End Sub
Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _ Handles
txtName.MouseLeave
'code for handling mouse leave on Name textbox
txtName.BackColor = Color.White txtName.ForeColor =
Color.Blue
End Sub

Private Sub txtAddress_MouseEnter(sender As Object, e As EventArgs) _ Handles


txtAddress.MouseEnter
'code for handling mouse enter on Address textbox txtAddress.BackColor =
Color.CornflowerBlue txtAddress.ForeColor = Color.White
End Sub
Private Sub txtAddress_MouseLeave(sender As Object, e As EventArgs) _ Handles
txtAddress.MouseLeave
'code for handling mouse leave on Address textbox
txtAddress.BackColor = Color.White txtAddress.ForeColor =
Color.Blue
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) _ Handles


Button1.Click
MsgBox("Thank you " & txtName.Text & ", for your kind cooperation") End SubEnd
Class
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −

Try to enter text in the text boxes and check the mouse events −
Handling Keyboard Events
Following are the various keyboard events related with a Control class −
●​ KeyDown − occurs when a key is pressed down and the control has focus
●​ KeyPress − occurs when a key is pressed and the control has focus
●​ KeyUp − occurs when a key is released while the control has focus
The event handlers​ of​ the​ KeyDown​ and​ KeyUp​ events​ get​ aargument

of type KeyEventArgs. This object has the following properties −
●​ Alt − it indicates whether the ALT key is pressed
●​ Control − it indicates whether the CTRL key is pressed
●​ Handled − it indicates whether the event is handled
●​ KeyCode − stores the keyboard code for the event
●​ KeyData − stores the keyboard data for the event
●​ KeyValue − stores the keyboard value for the event
●​ Modifiers − it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed
●​ Shift − it indicates if the Shift key is pressed
The event​ handlers​ of​ the​ KeyDown​ and​ KeyUp​ events​ get​ an
argument​ of type KeyEventArgs. This object has the following properties −
●​ Handled − indicates if the KeyPress event is handled
●​ KeyChar − stores the character corresponding to the key pressed
Example
Let us continue with the previous example to show how to handle keyboard events.
The code will verify that the user enters some numbers for his customer ID and age.
●​ Add a label with text Property as 'Age' and add a corresponding text box
named txtAge.
●​ Add the following codes for handling the KeyUP events of the text
box txtID. Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs)
_
Handles txtID.KeyUp

If (Not Char.IsNumber(ChrW(e.KeyCode))) Then MessageBox.Show("Enter


numbers for your Customer ID") txtID.Text = " "
End If End Sub
Add the following codes for handling the KeyUP events of the text box txtID. Private Sub
txtAge_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtAge.KeyUp

If (Not Char.IsNumber(ChrW(e.keyCode))) Then


MessageBox.Show("Enter numbers for age") txtAge.Text = " "
End If End Sub
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window –

If you leave the text for age or ID as blank or enter some non-numeric data, it gives a warning
message box and clears the respective text –
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces

. If you inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
Pros of using Adapter classes:
It assists the unrelated classes to work combinedly.

It provides ways to use classes in different ways

It increases the transparency of classes.


It provides a way to include related patterns in the class.

It provides a pluggable kit for developing an application.

It increases the reusability of the class.

The adapter​ classes​are​ found​ in java.awt.event, java.awt.dnd and javax.swing.event packages

. The Adapter classes with their corresponding listener interfaces are given below. java.awt.event Adapter

classes

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener

java.awt.dnd Adapter classes


DragSourceAdapter​ DragSourceListener

DragTargetAdapter​ DragTargetListener

javax.swing.event Adapter classes

ADAPTER CLASS​ LISTENER INTERFACE

MouseInputAdapter​ MouseInputListener

InternalFrameAdapter​ InternalFrameListener

Java WindowAdapter Example

In the following example, we are implementing the WindowAdapter class of AWT


and one its methods windowClosing() to close the frame window.

ADAPTEREXAMPLE.JAVA

// importing the necessary libraries


import java.awt.*;

import java.awt.event.*;

public class AdapterExample {

// object of
Frame
Frame f;
// class
constructor
AdapterExa
mple() {

// creating a frame with the title


f = new Frame ("Window Adapter");
// adding the WindowListener to the frame
// overriding the windowClosing() method
f.addWindowListener (new
WindowAdapter() {
public void windowClosing
(WindowEvent e) { f.dispose();

});

// setting the size, layout and


f.setSize (400, 400);​
f.setLayout (null); f.setVisible
(true);
}

// main method
public static void main(String[] args) {

new AdapterExample();
}

OUTPUT:

​ Java Inner Classes (Nested Classes)

Java inner class or nested class is a class that is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.Additionally, it can access all the members of the outer class, including private data
members and methods.

Syntax of Inner class

class Java_Outer_class{

//code
class Java_Inner_class{

//code
}

Advantage of Java inner classes

There are three advantages of inner classes in Java. They are as follows:

Nested classes represent a particular type of relationship that is it can access all the members (data
members and methods) of the outer class, including private.

Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.

Code Optimization: It requires less code to write.


Java Anonymous inner class
Java anonymous inner class is an inner class without a name and for which only a single object is
created. An anonymous inner class can be useful when making an instance of an object with certain
"extras" such as overloading methods of a class or interface, without having to actually subclass a
class.

In simple words, a class that has no name is known as an anonymous inner class in Java. It should be
used if you have to override a method of class or interface. Java Anonymous inner class can be
created in two ways:

1.​ Class (may be abstract or concrete).

2.​ Interface

Java anonymous inner class example using class

TESTANONYMOUSINNER.JAVA
abstract class Person{

abstract void eat();


}

class TestAnonymousInner{

public static void main(String args[]){ Person


p=new Person(){

void eat(){System.out.println("nice fruits");}


};

p.eat();
}

OUTPUT:

nice fruits

A Simple Swing Application, Applets

Java Applet

Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os
etc.

Drawback of Applet
Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the

Component.

Lifecycle of Java Applet

1.​ Applet is initialized.

2.​ Applet is started.

3.​ Applet is painted.

4.​ Applet is stopped.

5.​ Applet is destroyed.


Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.

public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.

1.​ public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.

2.​ public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.


public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can
be used for drawing oval, rectangle, arc etc.
How to run an Applet?
There are two ways to run an applet
1.​ By html file.

2.​ By appletViewer tool (for testing purpose).


3.​ Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.

//First.java
import java.applet.Applet;

import java.awt.Graphics;

public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

Java applets and applications Last

Updated: 2021-03-08

An applet is a Java™ program designed to be included in an HTML Web document. You can
write your Java applet and include it in an HTML page, much in the same way an image is included.
When you use a Java-enabled browser to view an HTML page that contains an applet, the applet's
code is transferred to your system and is run by the browser's Java virtual machine.

The HTML document contains tags, which specify the name of the Java applet and its Uniform
Resource Locator (URL). The URL is the location at which the applet bytecodes reside on the
Internet. When an HTML document containing a Java applet tag is displayed, a Java-enabled Web
browser downloads the Java bytecodes from the Internet and uses the Java virtual machine to
process the code from within the Web document. These Java applets are what enable Web pages to
contain animated graphics or interactive content.

You can also write a Java application that does not require the use of a Web browser.
For more information, see Writing Applets, Sun Microsystems' tutorial for Java applets. It includes
an overview of applets, directions for writing applets, and some common applet problems.

Applications are stand-alone programs that do not require the use of a browser. Java applications
run by starting the Java interpreter from the command line and by specifying the file that contains
the compiled application. Applications usually reside on the system on which they are deployed.
Applications access resources on the system, and are restricted by the Java security model.
Parameters passed to an applet
Steps to accomplish this task -:
●​ To pass the parameters to the Applet we need to use the param attribute of <applet> tag.
●​ To retrieve a parameter's value, we need to use the getParameter()
method of Applet class.

SIGNATURE OF THE GETPARAMTER() METHOD

●​ Method takes a String argument name, which represents the name of the
parameter which was specified with the param attribute in the <applet> tag.
●​ Method returns the value of the name parameter(if it was defined) else null is returned.

PASSING PARAMETERS TO AN APPLET.


o​ In the upcoming code, we are going to pass a few parameters like Name,
Age, Sport, Food, Fruit, Destination to the applet using param attribute in
<applet>
o​ Next, we will retrieve the values of these parameters using getParameter()
method of Applet class.

import java.awt.*;

/*

<applet code="Applet8" width="400" height="200">

<param name="Name" value="Roger">

<param name="Age" value="26">

<param name="Sport" value="Tennis">

<param name="Food" value="Pasta">

<param name="Fruit" value="Apple">

<param name="Destination" value="California">

</applet>

*/

public class Applet8 extends Applet

{String name; String age; String sport; String food; String fruit;
String destination;

public void init()

name = getParameter("Name"); age =


getParameter("Age"); food =
getParameter("Food"); fruit =
getParameter("Fruit");

destination = getParameter("Destination"); sport =


getParameter("Sport");

public void paint(Graphics g)

g.drawString("Reading parameters passed to this applet -", 20, 20); g.drawString("Name -" + name, 20, 40);

g.drawString("Age -" + age, 20, 60); g.drawString("Favorite fruit -" + fruit, 20,
80); g.drawString("Favorite food -" + food, 20, 100); g.drawString("Favorite
destination -" + name, 20, 120); g.drawString("Favorite sport -" + sport, 20,
140);

OUTPUT
In order to run our applet using the appletviewer, type the following command at the command
prompt-

JApplet class in Applet


As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The JA extends the
Applet class.
Example of EventHandling in JApplet:
import java.applet.*; import
javax.swing.*; import
java.awt.event.*;

public class EventJApplet extends JApplet implements ActionListener{ JButton


b;JTextField tf;

public void init(){


tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);

public void actionPerformed(ActionEvent e){


tf.setText("Welcome");
}

In the above example, we have created all the controls in init() method because it is invoked

only once.

myapplet.html

<html>
<body>
<applet code="EventJApplet.class" width="300" height="300">
</applet>
</body>
</html>
Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of MouseMotionListener.

Example of Painting in Applet:

import java.awt.*; import java.awt.event.*;import java.applet.*;

public class MouseDrag extends Applet implements MouseMotionListener{

public void init(){ addMouseMotionListener(this);


setBackground(Color.red);

}
public void mouseDragged(MouseEvent me){ Graphics
g=getGraphics(); g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}

public void mouseMoved(MouseEvent me){}

In the above example, getX() and getY() method of MouseEvent is used to get the
current x-axis and y getGraphics() method of Component class returns the object of Graphics.
myapplet.html
<html>
<body>
<applet code="MouseDrag.class" width="300" height="300">
</applet>
</body>
</html>
A Paint example
// Paint lines to a panel. import
java.awt.Graphics; import java.awt.Insets;

import javax.swing.JFrame; import javax.swing.JPanel;


import javax.swing.SwingUtilities;

// This class extends JPanel. It overrides

// the paintComponent() method so that random

// lines are plotted in the panel. class PaintPanel


extends JPanel {

Insets ins; // holds the panel's insets

// Construct a panel.

PaintPanel() {// w w w . d e m o2 s . c o m
}

// Override the paintComponent() method. protected void


paintComponent(Graphics g) {

// Always call the superclass method first. super.paintComponent(g);

int x, y, x2, y2;

// Get the height and width of the component. int height = getHeight();
int width = getWidth();

// Get the insets.

ins = getInsets();

x = width - ins.left;
y = height - ins.bottom; x2 = width -
ins.left;
y2 = height - ins.bottom;
// Draw the line.

g.drawLine(x-10, y-10, 100, 100);


}

// Demonstrate painting directly onto a panel. public class Main {

// Create the panel that will be painted. PaintPanel pp =


new PaintPanel(); Main() {

JFrame jfrm = new JFrame("Paint Demo"); jfrm.setSize(200, 150);

// Terminate the program when the user closes the application.


jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jfrm.add(pp);

// Display the frame.

jfrm.setVisible(true);
}

public static void main(String args[]) {

// Create the frame on the event dispatching thread. SwingUtilities.invokeLater(new


Runnable() {

public void run() {

new Main();

});

Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display a single
line of read only text. The text can be changed by an application but a user cannot edit it directly. It
inherits JComponent class.
JLabel class declaration

Let's see the declaration for javax.swing.JLabel class

public class JLabel extends JComponent implements SwingConstants, Accessible Java

JLabel Example

import javax.swing.*;

class LabelExample

Java JButton

The JButton class is used to create a labeled button that has platform independent implementation.
The application result in some action when the button is pushed. It inherits AbstractButton class.
JButton class declaration
Let's see the declaration for javax.swing.JButton class.
public class JButton extends AbstractButton implements Accessible Java JButton Example
import javax.swing.*;

public class ButtonExample {

public static void main(String[] args) { JFrame


f=new JFrame("Button Example"); JButton b=new
JButton("Click Here"); b.setBounds(50,100,95,30);
f.add(b); f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);} }
Output:

public class JButton extends AbstractButton implements Accessible Java


JToggleButton

JToggleButton is used to create toggle button, it is two-states button to switch on or off.

JToggleButton Example

import java.awt.FlowLayout;

import java.awt.event.ItemEvent;

import java.awt.event.ItemListener;
import javax.swing.JFrame;

import javax.swing.JToggleButton;

public class JToggleButtonExample extends JFrame implements ItemListener {

public static void main(String[] args) {

new JToggleButtonExample();
}

private JToggleButton button; JToggleButtonExample()


{

setTitle("JToggleButton with ItemListener Example"); setLayout(new


FlowLayout());
setJToggleButton(); setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private void setJToggleButton() { button = new


JToggleButton("ON"); add(button);

private void setAction() {


button.addItemListener(this);

public void itemStateChanged(ItemEvent eve) {

if (button.isSelected()) button.setText("OFF");

else

button.setText("ON");
}

Output
Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits
JToggleButton
class.
JCheckBox class declaration
Let's see the declaration for javax.swing.JCheckBox class.
public class JCheckBox extends JToggleButton implements Accessible Java

JCheckBox Example

import javax.swing.*;
public class CheckBoxExample

CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example"); JCheckBox
checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50); f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String args[])

{new CheckBoxExample();

}}

Output:
Next →← Prev

Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration

Let's see the declaration for javax.swing.JRadioButton class.


public class JRadioButton extends JToggleButton implements Accessible Java

JRadioButton Example

import javax.swing.*;

public class RadioButtonExample {


JFramef;

RadioButtonExample(){ f=new JFrame();

JRadioButton r1=new JRadioButton("A) Male"); JRadioButton


r2=new JRadioButton("B) Female");
r1.setBounds(75,50,100,30); r2.setBounds(75,100,100,30);

ButtonGroup bg=new ButtonGroup();


bg.add(r1);bg.add(r2);
f.add(r1);f.add(r2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String[] args) {

new RadioButtonExample();
}

Output:
SWING JTABBEDPANE :
We can see the tabbed pane in windows operating by opening the system properties like below.

Java JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we use a
scroll pane to display a large component or a component whose size can change dynamically.
JScrollPane Example
import java.awt.FlowLayout;
import javax.swing.JFrame;

import javax.swing.JScrollPane;
import javax.swing.JtextArea;

public class JScrollPaneExample {

private static final long serialVersionUID = 1L;

private static void createAndShowGUI() {

// Create and set up the window.


final JFrame frame = new JFrame("Scroll Pane Example");
// Display the window.
frame.setSize(500, 500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// set flow layout for the frame frame.getContentPane().setLayout(new


FlowLayout());
JTextArea textArea = new JTextArea(20, 20);
JScrollPane scrollableTextArea = new JScrollPane(textArea);
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROL LBAR_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
frame.getContentPane().add(scrollableTextArea);
}

public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() { createAndShowGUI();

});

}
OUTPUT

Java JList

The object of JList class represents a list of text items. The list of text items can be set up so that
the user can choose either one item or multiple items. It inherits JComponent class.
JList class declaration

Let's see the declaration for javax.swing.JList class.


public class JList extends JComponent implements Scrollable, Accessible Java JList Example
import javax.swing.*;

public class ListExample{

ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
l1.addElement("Item1");
l1.addElement("Item2");
l1.addElement("Item3");
l1.addElement("Item4"); JList<String> list =
new JList<>(l1); list.setBounds(100,100, 75,75);

f.add(list); f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])

new ListExample();

}}

Output:

Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
JComboBox class declaration
Let's see the declaration for javax.swing.JComboBox class.
public class JComboBox extends JComponent implements ItemSelectable, ListDataListener, Action

Java JComboBox Example


import javax.swing.*;

public class ComboBoxExample { JFrame


f;

ComboBoxExample(){

f=new JFrame("ComboBox Example");

String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
cb.setBounds(50, 50,90,20); f.add(cb);
f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}

public static void main(String[] args) {

new ComboBoxExample();
}

Output:

JMENUBAR, JMENU AND JMENUITEM


The JMenuBar class is used to display menubar on the window or frame. It may have several
menus.
The object of JMenu class is a pull down menu component which is displayed from the menu bar. It
inherits the JMenuItem class.

The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must
belong to the JMenuItem or any of its subclass.

JMenuBar class declaration


public class JMenuBar extends JComponent implements MenuElement, Accessible JMenu

class declaration
public class JMenu extends JMenuItem implements MenuElement, Accessible JMenuItem

class declaration

public class JMenuItem extends AbstractButton implements Accessible, MenuElement

Java JMenuItem and JMenu Example


import javax.swing.*;

class MenuExample

JMenu menu, submenu; JMenuItem i1, i2,


i3, i4, i5; MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example"); JMenuBar
mb=new JMenuBar();
menu=new JMenu("Menu"); submenu=new
JMenu("Sub Menu"); i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5"); menu.add(i1); menu.add(i2); menu.add(i3);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}

public static void main(String args[])

new MenuExample();

submenu.add(i4); submenu.add(i5);
menu.add(submenu);

}}

Output:
Java JDialog

The JDialog control represents a top level window with a border and a title used to
take some form of input from the user. It inherits the Dialog class.

Unlike JFrame, it doesn't have maximize and minimize buttons. JDialog class

declaration

Let's see the declaration for javax.swing.JDialog class.


public class JDialog extends Dialog implements WindowConstants, Accessible,
RootPaneC ontainer

Java JDialog Example


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new JLabel ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}

Output:

You might also like