0% found this document useful (0 votes)
29 views150 pages

Java Notes

The document provides a comprehensive overview of Java, detailing its history, features, and data types. It explains Java's popularity due to its open-source nature, platform independence, and robust architecture. Additionally, it covers variable types, operators, and conditional statements in Java programming.

Uploaded by

vijayanagani.sri
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)
29 views150 pages

Java Notes

The document provides a comprehensive overview of Java, detailing its history, features, and data types. It explains Java's popularity due to its open-source nature, platform independence, and robust architecture. Additionally, it covers variable types, operators, and conditional statements in Java programming.

Uploaded by

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

UNIT -II

UNIT I

FOUNDATIONS OF JAVA

History of Java:

What is Java?

Java is a computer programming language - Java can create all kinds web sites, enterprise applications, bank applications,
insurance applications, shopping sites, web application etc... that you could create using any conventional programming
language.
Java was created in 1991 by James Gosling et al. of Sun Microsystems. Initially called oak, in honor of the tree outside
Gosling's window, its name was changed to Java because there was already a language called oak.
So, they called it “Java.” May 23, 1995 – the official release date under the "Java" name. In 2009, the Java programming
language got a new owner when Sun Microsystems was acquired by Oracle. Currently, Oracle owns Java. According to data
from Oracle, more than 3 billion devices in the world run on Java.

Why java is popular?

 Java is open source software, it is free to download.


 Java is platform independent: java can run in any system line windows, Linux, mac etc.
 Java is architecture neutral: Programs written today are supported even if the system configuration is
changed, say processor is changed.
 Java is portable: can be executed in any platform without any prerequisite installations.

Buzzwords of Java

The features of java are:

 Simple
 Object Oriented
 Platform Independent
 Distributed
 Robust
 Secure
 Architecture Neutral
 Portable
 Interpreted
 High Performance
 Multithreaded
 Dynamic
Simple:
UNIT -II
Java is an object-oriented programming language with syntax and keywords almost identical to C++. When developing Java,
its creators took all of the good features of the existing object-oriented programming languages such as C++, Ada, and
Smalltalk, and removed most of their flaws and peculiarities.
If you are familiar with C++ you would know about clumsy features of C++: header files, pointer arithmetic (or even pointer
syntax), structures, unions, operator overloading, virtual base classes, and so on. All these clumsy features are cleaned-up in
java making it easier to learn.
Object Oriented: Any programming language if supports Encapsulation, Abstraction, Inheritance, Polymorphism then that
language is an object oriented programming language. E.g. java, C++
Platform Independent : Java is known for being platform-independent, which means that Java programs can run on any
device or operating system that has a Java Virtual Machine (JVM)
Distributed : The distributed nature of Java means that it supports the development of applications that can run across
multiple computers connected via a network. Java provides built-in tools and APIs that make it easier to create distributed
systems where different components of a program may run on different machines and communicate with each other.
Robust : The robust feature in Java means that Java is designed to write reliable, error-free, and crash-resistant programs.
It handles runtime errors, avoids memory leaks, and ensures strong memory management, making applications more
stable and secure.
Secure : Java is designed with security as a core feature. It provides a secure environment for developing and running
applications, especially those downloaded over a network (like applets, though less common today).

Architecture Neutral : The architecture neutral feature of Java means that compiled Java code (bytecode) can run on
any hardware platform, regardless of its underlying CPU architecture, such as x86, ARM, SPARC, etc. This allows Java
programs to be highly portable and consistent across systems.

Portable : The portable feature of Java means that Java programs can be easily moved and executed across different
platforms and environments without modification. Java achieves this by being both architecture-neutral and platform-
independent.

Interpreted : Java is considered both a compiled and an interpreted language. This unique combination is part of what
makes Java platform-independent and easy to run on many systems.

Java source code (.java file) is compiled into bytecode (.class file) by the Java compiler (javac).

This bytecode is not directly executed by the CPU. Instead, it is interpreted or executed by the Java Virtual Machine
(JVM).

High Performance : "High performance in Java" can refer to writing Java code and applications that are fast, efficient, and
scalable. Achieving high performance in Java involves understanding both language-level and JVM-level optimizations

Multithreaded: Multithreading in Java allows program to execute multiple tasks concurrently, taking advantage of multi-
core processors and improving performance, responsiveness, and scalability.

Dynamic : dynamic feature" in Java can refer to several capabilities that allow a program to adapt at runtime rather than
being strictly determined at compile time.
UNIT -II
Variables:

Variable in Java is the basic unit of storage. It acts as a container and is used to hold data values .The values held by the
variable can be change during the execution of the program. Every variable is assigned a data [Link], in simpler
terms, is a name given to a memory location. Variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type. Variables are containers for storing data values. A variable is a
memory location name where information is stored. Information is data it can be Alphabets, numbers, special
characters.
Avariableisdeclaredbyspecifyingthefollowingparameters: Datatype: Type of data
stored in the variable
VariableName:Auniquenameofthevariable

Value:The initial value stored in the variable


Int age=50;
Float weight=60;
In the above example, int is the data type, age is the name given to the variable, and 50 is the value. Similarly, float is the
data type, weight is the variable name and 50.60 is the value.
What is Declaration, Initialization?
Declaration tells about
a. What is the location name(i.e variable name)
b. Whattypeofdataitcan store
Initialization defines What information we stored in location.

1. Local Variable:
A variable declared inside the class and inside the method is called local variable .You can use this

Variable only within that methods and the other method in the class aren't even aware that the variable exists. A local
variable cannot be defined with "static" keyword. Local variable can access directly. Local variables prohibit the use of
access modifiers. These variables can be accessed only within the particular block.
Example: int id =0;// local variable id
2. Instance Variable:
A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared
as [Link]-specificandisnotshared among instances. Instance
variable can access by using object only. Access Modifiers can be used for instance variables. When no modifier is
UNIT -II
specified, the default modifier is used. Instance Variables have default values, 0 for numbers, false for Boolean, and
null for String object references. Instance variables that are declared in a class and not inside any function or main
method.
Example: int price;

Note: Local variable and Instance variable also called as non-static variables.
3. Static variable:
A variable that is declared as static is called a static variable. They are similar in nature to Instance
[Link] a static variable per
class is allowed. Static variable declared using static keyword. It cannot be local. You can create a single copy of the
static variable and share it among all the instances of the class. Memory allocation for static variables happens only
once when the class is loaded in the memory. Static variable can access directly. To access static variables, creating an
object of that class is not necessary.
Example: public static double salary; //static variable salary
Note: Instance variable and Static variable also called as Global variables.
Data types in java:
Data type is used to specify the type of data that variable can hold. A variable’s data type determines what operations can be
carried out on the variable’s data, as well as the amount of memory needed to hold the data.

Java has 2 types of data types

1. Primitive Types: byte, short, int, long, float, double ,char, Boolean
2. Non primitive Data Types: class, object, string, interface, string, Array.

The Primitive Types:


Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
Boolean. The primitive types are also commonly referred to as simple types, and both terms
will be used in this book. These can be put in four groups:

• Integers : This group includes byte, short, int, and long, which are for whole-valued
signed numbers.

• Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.

• Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.

• Boolean :This group includes Boolean, which is a special type for representing
true/false values.
UNIT -II
Integers: Java defines four integer types: byte, short, int and long. All of these are resigned positive and negative
values. Java does not support unsigned, positive-only integers. Many other computer languages support both
signed and unsigned integers.

Byte:
The smallest integer type is byte. This is a signed 8-bit type that has arranged from–128to 127.

Short:

Short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least- used
Java type. Here are some examples of short variable declarations:

shorts;

int:

The most commonly used integer type is int. It Is a signed 32-bit type that has a range from –2,147,483,648 to
2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index
arrays.

Long:

Long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the
desired value. The range of a long is quite large. That has a range from

-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

Floating-Point Types

Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional
precision.

Name Width in Bits Approximate Range


double 64 4.9e–324to1.8e+308
float 32 1.4e–045to3.4e+038

Float:

The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some
processors and takes half as much space as double precision.

Eg: float high temp, low temp;

Double :

Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double
precisionisactuallyfasterthansingleprecisiononsomemodernprocessorsthathavebeen optimized for high-speed
mathematical calculations.
UNIT -II

Characters:

In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in Java is
not the same as char in C or C++. In C/C++, char is 8bits wide in Java char is a 16-bit type. The range of a
char is 0 to 65,536. There are no negative chars.
Boolean:
Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or
false.

Non-Primitive DataTypes:

Non-primitive data types in Java are not predefined. Non-primitive types are created by the programmer and is not
defined by Java (except for String). Non-Primitive Data Type also known as Reference Data Types or derived data
types or advanced data types. The Reference Data Types will contain a memory address of variable values because the
reference types won’t store the variable value directly in memory. They are strings, arrays, classes and objects etc…

[Link]: Class is a template or blue print. Class is logical [Link] is a collection of objects. Class is a
collection of variables and methods. A document in which features and functions are defined
i.e. known as Class. Class is a keyword always writes in lowercase only. Class follows with Class
name and no semicolon and follows with body i.e. open brace and close brace({})inside that will
write code.
Syntax: class Class Name
Ex: class Student -Details
strings: Strings are used for storing text. A String variable contains a collection of characters
surrounded by double quotes.
Syntax: <String Type><string variable> = “<sequence_of_string>”;
Ex: String greeting="Hello";
Here String is data type, greeting is a variable and Hello is text.
The difference between a char and a string in Java is, that the string is designed to hold a sequence
of
characters in a single variable where as, a char is a collection of separate char type entities.
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value. To declare an array, define the variable type with square brackets:
Int[] marks;
We have now declared a variable that holds an array of integer.
Syntax: data type[] array name={value1,value2,value3,value4,value5};
Ex: int[]numbers={1, 2,3,4, 5};
UNIT -II

Operators:

Java provides a rich operator environment. Most of its operators can be divided into the following four
groups:arithmetic,bit wise,relational,and [Link] also defines some additional operators that handle certain
special operations.

1. Arithmetic Operators

Used for basic math operations:

Operator Description Example

+ Addition 5+3=8

- Subtraction 5-3=2

* Multiplication 5 * 3 = 15

/ Division 6/3=2

% Modulus (remainder) 5 % 3 = 2

2. Unary Operators

Operate on a single operand:

Operator Description Example

+ Unary plus (no effect) +a

- Unary minus (negation) -a


UNIT -II

Operator Description Example

++ Increment by 1 a++ or ++a

-- Decrement by 1 a-- or --a

! Logical NOT !true = false

3. Relational Operators

Compare two values, return boolean:

Operator Description Example

== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater or equal a >= b

<= Less or equal a <= b

4. Logical Operators

Operate on boolean values:

Operator Description Example

&& Logical AND true && false = false

` `

! Logical NOT !true = false

5. Bitwise Operators

Operate on bits of integer types:


UNIT -II

Operator Description Example

& Bitwise AND 5&3=1

` ` Bitwise OR

^ Bitwise XOR 5^3=6

~ Bitwise NOT ~5 = -6

<< Left shift 5 << 1 = 10

>> Right shift (signed) 5 >> 1 = 2

>>> Right shift (unsigned) -5 >>> 1 = large positive

6. Assignment Operators

Assign values to variables, with optional operation:

Operator Equivalent to Example

= Assignment a=5

+= a=a+b a += 3

-= a=a-b a -= 3

*= a=a*b a *= 3

/= a=a/b a /= 3

%= a=a%b a %= 3

7. Ternary Operator

Shorthand for if-else:

result = (condition) ? valueIfTrue : valueIfFalse;

Example:

int max = (a > b) ? a : b;


UNIT -II

8. Other Operators

Operator Description

instanceof Checks object type

. Member access (methods/fields)

?: Ternary conditional

Java Conditional Statements

Statements in Java program are executed sequentially in the order in which they appear. There are situations where we may
have to change the order of execution of statements based on certain conditions, or repeat the execution until certain specified
conditions are met. This involves a kind of decision making to see whether a particular condition has occurred or not and then
direct the interpreter (JVM) to execute certain statements accordingly. Conditional statements are used to change the
execution of statements based on conditions. In Java we have the following conditional statements:
1. if
2. if else
3. else if
4. switch

if statement

if statement syntax:

if(boolean_condition)
{
/* statement(s) will execute if the boolean condition is true */
}
If the boolean_condition evaluates to true, then statements inside if block will be executed. If the boolean_condition evaluates
to false, then statement immediately after if block will be executed. Statement inside if block can be single statement or
compound statement enclosed in curly braces (that is, a block). If the statement inside if block is single statement the curly
braces are optional.

if else statement
UNIT -II

if else statement syntax:

if(boolean_condition)
{
/* statement(s) will execute if the boolean condition is true */
}
else {
/* statement(s) will execute if the boolean condition is false */
}
else block is optional. If the boolean_condition evaluates to true, then the if block will be executed, otherwise else block will
be executed.

if-else-if Ladder

if-else-if ladder syntax:

if(boolean_condition 1) {
/* Executes when the boolean condition 1 is true */
}
else if( boolean_condition 2){
/* Executes when the boolean condition 2 is true */
}
else if( boolean_condition 3){
/* Executes when the boolean condition 3 is true */
}
else {
/* executes when the none of the above condition is true */
}
else if and else blocks are optional. If there are number of operations need to be done based on certain conditions then if
else ladder is useful. Ladder will be executed from top till any boolean_condition becomes true. If
any boolean_condition evaluates to true then that block will be executed. If no boolean_condition evaluates to true then
last else block will be executed.

Nested ifs

Nested ifs syntax:


if( boolean_condition 1)
{
/* Executes when the boolean condition 1 is true */
if(boolean_condition 2)
{
/* Executes when the boolean condition 2 is true */
UNIT -II
}
}
We can have if, if else, if else ladder inside any if, if else, if else ladder.

switch statement

switch statement syntax:

switch (expression) {
case value_expression:
statement(s);
break; /* optional */
case value_expression:
statement(s);
break; /* optional */
/* you can have any number of case statements */
default: /* Optional */
statement(s);
}
switch statement is used to execute a particular set of statements among multiple conditions. It is an alternative to
complicated if else if ladder conditions.
1. When switch block execution starts, this expression will be evaluated to a value.
2. The value_expression should be evaluated to a constant value of type same as the expression type in the switch.
3. Case block whose value is equal to the switch expression will be executed.
4. break is optional. Every case must end with break statement which will help to terminate and transfer the control
outside of switch block. If no break is used then execution will continue to next case.
5. A switch statement can have an optional default case, which must appear at the end of the switch. The default case
can be used for performing a task when none of the cases is true. No break is needed in the default case.

Nested switch statements

We can have switch blocks inside other switch block.


Nested switch statements Syntax:
switch (expression) {
case value expression:
switch (expression) {
case value expression:
statement(s);
break;
case value expression:
statement(s);
break;
UNIT -II
default:
statement(s);
}
break;
case value expression:
statement(s);
break;
default:
statement(s);
}

Iteration statements are also called as looping statements. By default all statements are executed sequentially in java program.
Iteration statements are used to repeat the statements until specified condition is met.
In Java, we have the following looping statements:
 while
 do...while
 for
 for-each

While loop

While loop syntax

while(condition)
{
statement(s);
}
The statement(s) will be executed as long as condition evaluates to true. Statement may be a single statement or a block of
statements.
The value of the variable involved in condition should be changing during every pass of the while loop. If it is not
changed, then the while loop enters into an infinite loop.

do-while

do-while syntax
do {
statement(s);
} while (condition);
statement(s) will be executed once. Then the condition will be evaluated, if it evaluates to true the do block will be executed
again. This process repeats until the given condition becomes false. statement(s) may be a single statement or a block of
statements
UNIT -II

The value of the variable involved in condition should be changing during every pass of the while loop. If it is not
changed, then the while loop enters into an infinite loop.

for loop

for loop syntax


for (initialization; boolean_expression; update_statement)
{
//body of the loop;
}

for statement has the following properties:


 The two semicolons are required and create three sections: an initialization statement, a boolean expression,
and an update statement.
 The initialization step occurs once at the beginning of the loop.
 The boolean_expression must evaluate to true or false.
 The initialization and update_statement sections can contain multiple statements, separated by commas.
 Any variables declared in the initialization step are local variables in for loop and go out of scope when the
loop finishes.

Below is the flow of control in for loop

 The initialization statement is executed first, and only once. This step allows you to declare and initialize any
loop control variables.
 Next, the condition (boolean_expression) is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next statement just after for loop.
 After the body of for loop executes the flow of control jumps back up to the update_statement. This
statement allows you to update any loop control variables.
 The condition (boolean_expression) is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, for
loop terminates.

for loop example

package com.java4coding;

public class HelloWorld {


public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
[Link]("The number is " + i);
}
}
UNIT -II
}

Jump Statements in Java

Jump statements are used to jump the control to another part of our program depending on the conditions. Jump statements
are useful to break the iterations loops when certain conditions met and jump to outside the loop. These statements can be
used to jump directly to other statements, skip a specific statement and so on.
Following are the jump statements in java.
 break
 continue
 return
 goto (reserved for future use, currently not in use)
break statement
break statement syntax
break;
If break statement is encountered then execution of its immediate surrounding block will be skipped control will go to next
statement immediately after that block.
break statement example
package com.java4coding;

public class HelloWorld {

public static void main(String[] args) {


for (int i = 1; i <= 5; i++) {
if (i == 3 ) {
break;
}
[Link]("The number is " + i);
}
}
}

Output:

The number is 1
The number is 2

labeled break statement

We can also use the break statement with a label. The break statement is used when we want to transfer the flow of control
from an inner block to an outer block, but when we want the flow of control to exit the outer block then we use a labeled
break statement.
UNIT -II

labeled break statement example

package com.java4coding;

public class HelloWorld {


public static void main (String args[])
{
boolean a=true;
a:
{
b:
{
c:
{
[Link]("Before break");
if(a)
break a;
[Link]("This will not execute");
}
}
[Link]("After break");
}
}

Output:

Before break
After break
continue statement
continue statement syntax
continue;
If continue statement is encountered then execution of remaining statements in its immediate surrounding block will be
skipped. Unlike break, it skips the remaining statements not the complete block, so if the block is iterative block then control
goes to the beginning of the loop.
continue statement example
package com.java4coding;

public class HelloWorld {


UNIT -II

public static void main(String[] args) {


for (int i = 1; i <= 5; i++) {
if (i == 3 ) {
continue;
}
[Link]("The number is " + i);
}
}

}
Output:
The number is 1
The number is 2
The number is 4
The number is 5
return
This is used to return value from a method. Once method returns a value, further statements after return statements will be
skipped.
More about this will be studied later while discussing about methods.
package com.java4coding;

public class HelloWorld {

public static void main(String[] args) {


[Link](printName());
}

public static String printName() {


String names[] = { "Manu", "Advith", "Likitha" };

if ([Link] == 3) {
return "Advith";
}

for (String name : names) {


[Link](name);
}
UNIT -II

return "Manu";
}

Output:

Advith

What is Class and Object in Java

Class is a user defined data type. Class is one among four user defined data types. Any concept you wish to implement in a
Java program must be encapsulated within a class. In object oriented programming, we design a program using objects and
classes. Object is the physical entity whereas class is the logical entity.

Members of class

Class can have any of the below members:


1. Data members/fields/field variables
2. Block
3. Methods
4. Constructor
5. Inner class

We will study in detail about each member of a class in coming chapters.

A Simple Example for Class

class Box {
double width;
double height;
double depth;
UNIT -II
}

Declaring or creating Objects using new keyword

Declaring Objects using new involves two steps.


1. Declaring 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. Acquiring an actual, physical copy of the object and assign it to variable. We can do this using
the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object at run
time and returns a reference to variable. This reference is, more or less, the address in memory of the object allocated
by new. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically allocated.
Declaring Objects using new has this general form

Java Method - How to Create Method in Java

Java method is a collection of statements that are grouped together to perform an operation. Methods represent the behaviors
of the object. Methods can take input in the form of parameters, performs the operation on input and returns a result to the
caller. A method will be executed by a call to the method.

Creating a Method

Method has the following syntax (method definition)


Access_specifier Non_Access_specifier returntype methodName (type1 pmtr1, type2 pmtr2, type3 pmtr3..)
{
//Method body
return exp;|return;
}
Access specifier: The possible values of the access specifier are public, private, protected, or default access
Non_Access_specifier: The possible values for these specifiers are static, final, abstract, native, and synchronized. A
method might not use any of these specifiers, or a method might use more than one of them.
The order of the access specifiers and optional non access specifiers is arbitrary. However, you will almost always see
the access specifier appear first in a method signature because it is the preferred style among Java programmers.
Non_Access_specifier Access_specifier returntype methodName (type1 pmtr1, type2 pmtr2, type3 pmtr3..)
{
UNIT -II

//Method body
return exp;|return;
}

Constructors in java
A constructor in Java is a special method that is called when an object is created. Its main purpose is to initialize the new
object.

Default constructor syntax

Access_specifier ClassName ()
{
//Constructor body
}
Syntax to create object: ClassName classVar = new ClassName();

Parameterized constructor syntax

Access_specifier ClassName (type1 pmtr1, type2 pmtr2, type3 pmtr3..)


{
//Constructor body
}
Syntax to create object: ClassName classVar = new ClassName (arg1, arg2, arg3..);

Example

package com.java4coding;

public class ConstructorDemo {

public ConstructorDemo ( ) {
[Link]("Default Constructor");
}

public ConstructorDemo (String message ) {


[Link]("Parameterized Constructor");
}

public ConstructorDemo (int num) {


[Link]("Parameterized Constructor");
}
UNIT -II

public static void main(String... args) {


ConstructorDemo constructorDemo1 = new ConstructorDemo();

ConstructorDemo constructorDemo2 = new ConstructorDemo("Hello");

ConstructorDemo constructorDemo3 = new ConstructorDemo(100);


}
}

Access Modifiers

1. An access modifier specifies who can access them. There are four access modifiers used in java. They are
public, private, protected, default (no keyword is used). Default access is also sometimes referred as ‘package-
private’ or ‘friendly’ access.
2. Access modifiers cannot be used for local variables.
3. Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and
member level access modifiers.
Class level access modifiers (java classes only)
Only two access modifiers is allowed, public and default
1. If a class is ‘public’, then it CAN be accessed from ANYWHERE.
2. If a class has no modifier ( default) then it CAN ONLY be accessed from ‘same package’
In the below example you can see class B is having default no modifier. This class is not accessible from outside the package
in class Hello World. But class B is accessible within same package from class C. Class A is having public access specifier

which is accessible from


anywhere.
UNIT -II

Member level access modifiers

1. Member level access modifiers apply to methods, constructors, fields.

Access modifier Public Protected Default Private protected private


Access Location
Same class Yes Yes Yes Yes Yes
Subclass in same package Yes Yes Yes Yes No
Other class in same package Yes Yes Yes No No
Subclass in other package Yes Yes No Yes No
Other class in other package Yes No No No No
2. Private and protected can be declared together. This gives visibility level in between private and protected.
3. Always declare constructors as public. (Try to declare).

In the below example you can see how the different member level access specifiers act on usage.

A source code file in Java can contain exactly one public class, and the name of the file must match the name of the
public class with a .java extension.
You can declare more than one class in a .java file, but at most only one class can be declared public. The name of the
source code file must still match the name of the public class. If there are no public classes in the source code file, the
name of the file is arbitrary.
UNIT -II

Generics in Java

Generics enable you to define classes, methods, or interfaces with placeholders for the type of data they operate on. Instead of
using Object and casting later, generics help avoid runtime errors by catching type mismatch at compile time.

Benefits:

 Type safety: Avoid ClassCastException at runtime.


 Code reusability: Write a class or method once and use it for different types.
 Cleaner code: No need for explicit casting

The most commonly used type parameter names are:

 E – Element (used extensively by the Java Collections Framework, for example Array List, Set etc.)
 K – Key (Used in Map)
 N – Number
 T – Type
 V – Value (Used in Map)
 S,U,V etc. – 2nd, 3rd, 4th types

Java Annotation

Annotations are user defined data type. All annotations extend [Link] interface. Annotations start
with ‘@’. Using annotations we can attach additional information (officially called attributes) to class, interface, method or
variable. These additional information conveyed by annotation can be used by a development environment, java compiler or
a runtime environment.
We can place Java annotations above classes, interfaces, methods, method parameters, fields and local variables. An
annotation which is defined for class should be used over class and cannot be used for methods. But there are some
annotations which are defined to use either at class level or method level. There are some annotations which are defined such
that they can be used for variable and as well as methods. It all depends on the ways annotations are defined. Usage of
annotation to any member should be as per the design. Annotations allow programmer to add metadata to the java class itself
instead of providing metadata through XML documents.

We can define 3 types of annotations

1) Marker annotation: It is similar to marker interface. These annotations contain no members and no data. @Override is an
example of Marker Annotation. If we write marker annotation we must write the code at classes, interfaces, methods,
method etc... at which annotation is used to process the annotation.
Example: DemoAnnotation();
2) Single value annotation: When we define an annotation with one member then it is called single value annotation.
Specifying the name of the member is optional when we specify the value for that member.
Example: DemoAnnotation(“Hello”);
UNIT -II
3) Multiple value annotation: When we define an annotation with two or more member then it is called multiple value
annotation. Specifying the name of the members is mandatory when we specify the value for that member.
Example: DemoAnnotation(message = “Hello”, sender = “java4coding”, receiver = “Manu”);

n Java, the String class is a fundamental and widely used class for handling sequences of characters. Here's an overview of
the String class and related classes:

1. String Class

 Immutable: Once a String object is created, it cannot be changed.


 Defined in: [Link] package.
 Usage:

java
CopyEdit
String s = "Hello, World!";

 Common Methods:
o length(): Returns the length of the string.
o charAt(int index): Returns the character at the specified index.
o substring(int start, int end): Returns a substring.
o equals(Object obj): Compares two strings for content equality.
o compareTo(String another): Lexicographically compares two strings.
o toLowerCase(), toUpperCase()
o trim(): Removes whitespace from both ends.
o replace(), split(), contains(), etc.

2. StringBuilder Class

 Mutable: Allows modification of characters.


 Faster for concatenation than String when many modifications are involved.
 Usage:

java
CopyEdit
StringBuilder sb = new StringBuilder("Hello");
[Link](" World!");

 Common Methods:
o append(), insert(), delete(), reverse(), toString()
UNIT -II

3. StringBuffer Class

 Similar to StringBuilder but thread-safe (synchronized).


 Slightly slower due to synchronization overhead.
 Usage:

StringBuffer sb = new StringBuffer("Hello");


[Link](" World!");
Inner classes in java:

In Java, inner classes are classes defined within another class. They are used to logically group classes that are only used in
one place, and they can access members of the outer class—including private ones.

Here’s a breakdown of the types of inner classes in Java:

1. Non-static Nested Class (Inner Class)

 Associated with an instance of the outer class.


 Can access all members (including private) of the outer class.

class Outer {
private String msg = "Hello";

class Inner {
void showMessage() {
[Link](msg); // Accessing outer class member
}
}
}

2. Static Nested Class

 Does not require an instance of the outer class.


 Can only access static members of the outer class.

class Outer {
static String msg = "Hello";

static class Nested {


UNIT -II
void showMessage() {
[Link](msg);
}
}
}

3. Local Inner Class

 Defined inside a method, constructor, or block.


 Scope is restricted to the block where it is defined.
 Can access local variables only if they are effectively final.

class Outer {
void display() {
String localVar = "Local";

class LocalInner {
void print() {
[Link](localVar);
}
}

LocalInner inner = new LocalInner();


[Link]();
}
}

4. Anonymous Inner Class

 A one-time use class without a name.


 Often used when instantiating an interface or abstract class.

abstract class Greeting {


abstract void sayHello();
}

class Main {
public static void main(String[] args) {
Greeting g = new Greeting() {
void sayHello() {
[Link]("Hello from anonymous inner class!");
UNIT -II
}
};
[Link]();
}
}
Oop principles:

Encapsulation concept:

Encapsulation in Java is a core principle of Object-Oriented Programming (OOP) that involves bundling data (variables) and
the methods that operate on that data into a single unit, typically a class. This mechanism restricts direct access to an object's
internal state and controls how that state can be accessed or modified.

Key aspects of encapsulation in Java:

 Data Hiding:

Encapsulation promotes data hiding by declaring class variables (attributes) as private. This prevents direct access to these
variables from outside the class, protecting them from unintended modification.

 Controlled Access:
To allow controlled access to the private data, public methods, commonly known as "getters" and "setters," are provided.
 Getters (Accessor Methods): These methods retrieve the value of a private variable.

 Setters (Mutator Methods): These methods modify the value of a private variable, often including validation logic to ensure
data integrity.
How encapsulation is achieved:

 Declare class variables with the private access modifier.

 Create public getter methods to read the values of these private variables.

 Create public setter methods to modify the values of these private variables, allowing for data validation or transformation
before assignment.
Benefits of encapsulation:

 Data Integrity:

Prevents unauthorized or accidental modification of an object's internal state.

 Modularity:

Promotes a clear separation of concerns, making code easier to understand, maintain, and debug.

 Flexibility and Maintainability:

Allows for changes to the internal implementation of a class without affecting external code that uses the class, as long as
the public interface (getters and setters) remains consistent.

 Security:
Enhances the security of the application by controlling data access.
UNIT -II

This Keyword:

1. this is a keyword in java.


2. this is a reference variable which refers to the current object.
3. this keyword is used to access the members of the class within the same class and can be used only to access
instance members.
4. this cannot be used to access static members of the class. this also cannot be used in static context.
Usage of java this keyword
1. this keyword can be used to access the instance variables
2. this keyword can be used to access the constructors
3. this keyword can be used to access the methods

Accessing the instance variables using this

this keyword is used to resolve the conflicts between instance variables and local variables.
package com.java4coding;

public class Demo {


int height;
int width;
int length;

public Demo ( ) {
}

public Demo (int height, int width, int length ) {


[Link] = height;
[Link] = width;
[Link] = length;
}

public void setValues (int height, int width, int length) {


[Link] = height;
[Link] = width;
[Link] = length;
}
}
UNIT -II

Inheritance in Java

A class should be closed for modification but open for extension. We should not modify any class; we can add additional
features to an existing class without modifying it. Inheritance is one concept to achieve this. Inheritance is a concept of
inheriting the properties of one class (super class) into another class (sub class) when there “IS” a relationship between
classes. It is a process of reusing existing class functionality in new class. The existing class is called super class/parent
class/base class and the new class is called subclass/child class/derived class. All the members of super class will be inherited
into subclass (except constructor and private members) and can be accessed directly in subclass. Super classes are generalized
classes, subclasses are specialized classes. Super class, subclass and client class all should be in same folder; otherwise need
to deal with packages.
Syntax to create subclass
class SubclassName extends SuperclassName {
//Members of subclass
}
Different types of Inheritance
1. Simple Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1) Simple Inheritance
 In simple inheritance there will be exactly one super class and one subclass i.e. subclass will get the
functionality from exactly only one super class.
 It is supported by class data type.

class Box {
double width;
double height;
double depth;

// constructor clone of an object, used to copy values from one object to


// another object.
Box(Box ob) {// pass object to constructor
width = [Link];
UNIT -II
height = [Link];
depth = [Link];
}

// constructor used when all dimensions specified


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions specified


Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}

// constructor used when cube is created


Box(double len) {
width = height = depth = len;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

class BoxWeight extends Box {


double weight;

BoxWeight(double w, double h, double d, double m) {


width = w;
height = h;
depth = d;
weight = m;
}
UNIT -II
}

class DemoBoxWeight {
public static void main(String args[]) {
Box supbox1 = new Box(1, 2, 3);
Box supbox2 = new Box(supbox1); // This will be error if constructor clone is not present
double vol;
vol = [Link]();
[Link]("Volume of supbox1 is " + vol);
vol = [Link]();
[Link]("Volume of supbox2 is " + vol);
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
[Link]("Weight of mybox1 is " + [Link]);
[Link]();
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
[Link]("Weight of mybox2 is " + [Link]);
}
}
Output:
Volume of supbox1 is 6.0
Volume of supbox2 is 6.0
Volume of mybox1 is 3000.0
Weight of mybox1 is 34.3

Volume of mybox2 is 24.0


Weight of mybox2 is 0.076
2) Multilevel Inheritance
 In multilevel inheritance one super class can have many sub classes.
 One subclass can have many indirect super classes i.e. one is direct super class all remaining are indirect
super classes.
 It is supported by class data type.
UNIT -II

class Aves{
public void nature() {
[Link]("Generally, Aves fly");
}
}
class Bird extends Aves{
public void eat(){
[Link]("Eats to live");
}
}
public class Parrot extends Bird{
public void food(){
[Link]("Parrot eats seeds and fruits");
}
public static void main(String args[]){
Parrot p1 = new Parrot();
[Link](); // calling its own
[Link](); // calling super class Bird method
[Link](); // calling super class Aves method
}
}
Output:
Parrot eats seeds and fruits
Eats to live
Generally, Aves fly
3) Hierarchical Inheritance
 In this one super class can have many direct sub classes.
 It is supported by class data type.
UNIT -II

class Aves{
public void fly() {
[Link]("Generally, aves fly");
}
}
class Parrot extends Aves{
public void eat(){
[Link]("Parrot eats fruits and seeds");
}
}
class Vulture extends Aves{
public void vision(){
[Link]("Vulture can see from high altitudes");
}
}
public class FlyingCreatures{
public static void main(String args[]){
Parrot p1 = new Parrot();
[Link]();
[Link]();
Vulture v1 = new Vulture();
[Link]();
[Link]();
}
}
Output:
Parrot eats fruits and seeds
Generally, aves fly
Vulture can see from high altitudes
Generally, aves fly
4) Multiple Inheritances
 In this one sub class can have many direct super classes.
 Multiple inheritance is not supported by java with class data type. But it is supported with interface data type
UNIT -II

We can achieve partial multiple inheritance with the help of interfaces.


Example:
public class FerrariF12011 extends Ferrari implements Car, Automobile {//…}
5) Hybrid Inheritance
 It is the combination of multiple, multilevel and hierarchical inheritance.
 Hybrid inheritance is not supported by java with class data type. But it is supported with interface data type.

super keyword in Java

super is reference variable which refers to the immediate super class object. super keyword is used to access the instance
members of the super class from sub class and cannot be used to access the static members of the class or super keyword
cannot be used in static context. super is used to access the following members of the super class from subclass.
1.
1. Variables
2. Methods
3. Constructors
super to access variables
All the members of super class will be inherited into subclass (except constructor and private members) and can be accessed
directly in subclass. If subclass has the variable with the same name as in super class, it creates name conflict. super keyword
is used to resolve the conflict between super class instance variables and subclass instance variables
class Employee {
String name = "Manu";
}

class Manager extends Employee {


String name = "Manu Manjunatha";

void printName () {
[Link](name);// prints Manu
[Link]([Link]);// prints Manu Manjunatha
}
UNIT -II
}

Example:
public class FerrariF12011 extends Ferrari implements Car, Automobile {//…}
Polymorphism in java

Polymorphism is a core concept in object-oriented programming (OOP) that allows objects of different classes to be treated
as objects of a common superclass. It enables a single interface to represent different underlying forms (data types).

There are two main types of polymorphism:

1. Compile-time Polymorphism (Static Binding)


o Achieved through method overloading and operator overloading.
o The method to be executed is determined at compile time.
o Example (Java):

class Math {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}

2. Run-time Polymorphism (Dynamic Binding)


o Achieved through method overriding.
o The method to be executed is determined at runtime, based on the object.
o Example (Java):

class Animal {
UNIT -II
void sound() {
[Link]("Animal makes sound");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

public class Test {


public static void main(String[] args) {
Animal a = new Dog();
[Link](); // Output: Dog barks
}
}

Benefits of polymorphism:

 Promotes code reusability.


 Enhances flexibility and scalability.
 Simplifies code maintenance.

Method overriding methods:

Over ridden methods allow Java to support run-time polymorphism. Polymorphism is essential to object-
oriented programming for one reason: it allows a general class to specify methods that will be common to all
of its derivatives, while allowing subclasses to define the specific implementation of some or all of those
methods.
Overridden methods are another way that Java implements the “one interface, multiple methods” aspect of
polymorphism.

The following program creates a superclass called Figure that stores the dimensions of a two-
dimensional object. It also defines a method called area( ) that computes the area of an object.
The program derives two subclasses from Figure. The first is Rectangle and the second is
Triangle. Each of these subclasses overrides area( ) so that it returns the area of a rectangle and a
triangle, respectively.

// Using run-time polymorphism. class Figure {


UNIT -II
double dim1; double dim2;

Figure(double a, double b) { dim1 = a;

dim2 = b;

double area() {

[Link]("Area for Figure is undefined."); return 0;

class Rectangle extends Figure { Rectangle(double a, double b)


{

super(a, b);

// override area for rectangle double area() {

[Link]("Inside Area for Rectangle."); return dim1 * dim2;

class Triangle extends Figure { Triangle(double a, double b) {

super(a, b);

// override area for right triangle double area() {

[Link]("Inside Area for Triangle."); return dim1 * dim2 / 2;

}
UNIT -II

class FindAreas {

public static void main(String args[]) { Figure f = new


Figure(10, 10); Rectangle r = new Rectangle(9, 5);

Java abstract class vs. interface

In this chapter you learn the differences between java abstract class and interface.

Abstract Class Interface

Abstract class can contain the following members: An interface can contain the following members:
1. Instance and static variables 1. public static final variables
2. Instance and static block 2. public abstract methods
3. Concrete methods (Instance and
static)
4. Abstract methods
5. Constructor
Abstract method inside abstract class should have Abstract method inside interface is not necessary to have abstract
abstract keyword. keyword. Compile will add abstract keyword to all methods of
abstract class A { interface.
abstract int add(int a, int b); interface A {
} int add(int a, int b);
}
Implementation class has to extend abstract class Implementation class has to implement an interface using
using “extends” keyword. "implements” keyword.
abstract class A { interface A {
abstract int add(int a, int b); int add(int a, int b);
} }
class B extends A { class B implements A {
int add(int a, int b) { public int add(int a, int b) {
return a + b; return a + b;
} }
} }
Implementation class can extend only one abstract Implementation class can implement any number of interfaces.
class. interface A {
abstract class A { int add(int a, int b);
abstract int add(int a, int b); }
} interface B {
UNIT -II

class B extends A { int subtract (int a, int b);


int add(int a, int b) { }
return a + b; class C implements A, B {
} public int add(int a, int b) {
} return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
It is used for doing partial implementation; It can It is completely specification, has zero percent implementation.
have complete or partial implementation. Abstract Interface can have only abstract methods.
class can have both abstract and concrete methods.
It supports abstraction to a smaller extent. Can be It supports 100% abstraction.
100% abstraction if all the methods in it are abstract
methods.
Multiple inheritance cannot be achieved using Using interface you can achieve multiple inheritance.
abstract class.
Abstract class can implement interface. Interface cannot implement anything.
An abstract class can extend another Java class and Interface can extend another interface.
implement multiple Java interfaces.
UNIT -II

UNIT II

Exception and Error:

Errors:
It is a runtime error which will cause the program to terminate. You cannot handle it. Error will
terminate the program.
Actually, these are not exceptions at all, but Sun Micro systems says it is a type of Exception .These are
problems that arise beyond the control of the user or the programmer.
E.g. Out Of Memory Error, Virtual Machine Error, Assertion Error etc.

Exceptions

It is a runtime error which can cause the program to terminate. We can handle the exception and if handled
program does not terminate and execution continues normally. Exception is an object thrown by a method.

Example:
Arithmetic Exception
int a=50/0;//Arithmetic Exception
Number Format Exception
Boolean b=true;
Int I=[Link](s);
Null Pointer Exception
Employee e1=null;
[Link] ([Link]);//Null Pointer Exception
Array Index Out Of Bounds Exception
Int a []=new int[10];
[Link] (a[20]); //Array Index Out Of Bounds Exception
Checked exceptions: If checked exception is present in program, then before doing anything to program we
need to do something to exception. Since we have to do something to exception before doing anything to
program it is a checked exception.
UNIT -II

Unchecked exceptions: If unchecked exception is present in program, then we can do anything to program
without doing anything to exception. Since we can proceed with program execution without doing anything
to exception it is an unchecked exception.

Hierarchy of Exception classes

How to handle Exception?

Five keywords used in Exception handling

1. try
2. catch
3. finally
4. throw
5. throws

Try block

1. Enclose the code that might throw an exception in try block. Code within a try/catch block is
referred to as protected code.
2. It must be used within the method and must be followed by either catch or finally block.
3. If exception doesn’t occurs inside try block, then catch block will be skipped.
4. If exception occurs inside try block then remaining statements will be skipped in try block,
Control jumps to catch block.

Syntax of try with catch block

try {
...
} catch (Exception_class_Name reference) {
}

Syntax of try with finally block


UNIT -II

try {
...

} finally {
}

Catch block

1. Catch block is used to handle the Exception. It must be used after the try block.
2. A catch statement involves declaring the type of exception you are trying to catch. If an
3. exception occurs in protected code, the catch
4. block (or blocks) that follow the try is checked. If the type of exception that occurred is listed
5. in a catch block, the exception is passed
6. to the catch block much as an argument is passed into a method parameter. If you say you
7. want to catch a NullPointerException and an Arithmetic Exception occurs, you will not
8. catch the Arithmetic Exception.
9. If you say you want to catch an Exception, then you will catch every exception that might arise.
Remember, all exceptions are child
10. Classes of Exception, so through polymorphism, all exceptions are of type Exception.
UNIT -II

Multiple catch blocks:


1. One try block can have multiple catch statements. In some cases, more than one exception can
2. occur in a try block, but always only one type of an exception object will be created at a time.
3. To handle such situations one try block can have multiple catch statements. But since always
4. only one type of an exception object will be created in the try block, only one catch block gets
executed.
5. When an exception is thrown, each catch statement is inspected in order and the first one which
matches that exception type will get executed.
6. All catch blocks must be ordered from most specific to most general i.e. catch for Arithmetic
Exception must come before catch for Exception.
7. Even though class Exception can handle all the exceptions, it is always advisable to write the
specific type of Exception in the catch block. Because after catching the Exception, next we have to
8. Check the type of Exception which has occurred, and then write the logic to fix the error for that
exception.
UNIT -II

Nested try block


Nested try block is a try block within a try block is known as nested try block. Sometimes a situation may
arise where a part of a block may cause one
error and the entire block itself may cause another error. In such cases, exception handlers have to be nested

Nested try block syntax


...
try {
Statement 1;
Statement 2;
try {
Statement 1;
Statement 2;
}
Catch (Exception e) {
}
}
Catch (Exception e) {
}
....

Nested try block Example


class Exception Handling {
public static void main(String args[]) {
try {
try {
[Link]("going to divide");
int b = 39 / 0;
} catch (Arithmetic Exception e) {
[Link](e);
}
try {
int a[] = new int[5];
a[5] = 4;
} catch (ArrayIndexOutOfBoundsException e) {
[Link](e);
}
[Link]("other statement");
} catch (Exception e) {
[Link]("handled");
}
[Link]("normal flow..");
}
}
Output:
going to divide
UNIT -II

[Link] Exception: / by zero


[Link]: 5
other statement
Normal flow..

Java finally block

The finally block is a block that is always executed. It is mainly used to perform some important tasks such as
closing connection, closing stream etc.

Note: Before terminating the program, JVM executes finally block (if any). finally must be followed by try or
catch block.

Why use finally block?

finally block can be used to put "cleanup" code such as closing a file, closing connection , to release resources
etc…

Case 1: Program in case exception does not occur


class Exception Handling {
public static void main(String args[]) {
try {
int data = 25 / 5;
[Link](data);
} catch (Null Pointer Exception e) {
[Link](e);
} finally {
[Link]("finally block is always executed");
}
[Link] ("rest of the code...");
}
}
UNIT -II

Output:
5
finally block is always executed
rest of the code...

Case 2: Program in case exception occurred but not handled


class Exception Handling {
public static void main(String args[]) {
try {
int data = 25 / 0;
[Link](data);
} catch (NullPointerException e) {
[Link](e);
} finally {
[Link]("finally block is always executed");
}
[Link] ("rest of the code...");
}
}
Output:
finally block is always executed
Exception in thread "main" [Link] Exception: / by zero
at [Link] [Link](Exception [Link])

Case 3: Program in case exception occured and handled


class Exception Handling {
public static void main(String args[]) {
try {
int data = 25 / 0;
[Link](data);
} catch (Arithmetic Exception e) {
[Link](e);
} finally {
[Link]("finally block is always executed");
}
[Link] ("rest of the code...");
}
}
Output:
[Link] Exception: / by zero
finally block is always executed
rest of the code...
Rule: For each try block there can be zero or more catch blocks, but only one finally block.
Note: 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).
UNIT -II

What are the different conditions that a method gets terminated?


There are three conditions or reasons for which method gets terminated.
1. return keyword. (control returns to calling line of the caller method)
2. An exception occurs (control returns to the catch block of the caller method)
3. [Link]() method (program terminates)

Java throw and throws

throw

The throw keyword is used to explicitly throw an exception. When one method calls another method (Either
main method invoking other methods or other method invoking some other method) exception object is
thrown to the caller method. Execution stops immediately after the throw statement and any subsequent
statements are not executed. We can throw either checked or unchecked exception (sub classes of class
Throwable). The throw keyword is mainly used to throw custom exception (generally).

Example of throw keyword

In this example, we have created the validate method that takes integer value as a parameter. This value is
treated as age of a person. If the age is less than 18, we are throwing the Arithmetic Exception otherwise
print a message welcome to vote.

Throwing same exception which is caught is known as rethrowing an exception.


Catch (Whatever Exception e) {
throw e;
}

Throws

In the above program of voting we want exception to occur mandatorily if age is below 18, otherwise any
person with age below 18 can vote.
UNIT -II

In the program we used Arithmetic Exception which is unchecked exception. But if any checked
exception is used the program will not compile
at all. So in order to compile the program and to arise checked exception during run time we use throws
keyword to declare exception.
If I try to withdraw more money than I have in my checking account, exception should occur and should
Inform me that I am trying to overdraft. If exception doesn’t occur and fails to stop me from ignoring my
Overdraft then i can just go right on spending more money and then plead ignorance when my overdraft
Statement comes in the mail. I can tell the bank that I didn’t check the return value of the withdraw () method.
In this case if checked exception is used then program will not compile at all. So in order to compile the
Program and to arise checked exception during run time we use throws keyword to declare
Exception.

When do you handle an exception and when do you declare an exception?


The answer is based on design decisions. Do you want a method to deal with a problem, or do you want the
problem to be passed on to the caller of the
Method?
Suppose that I walk into my bank and make a deposit (by invoking a deposit () method), but the teller is having
problems with his computer.
That should not be my problem. In this case, the deposit () method should handle this exception and fix the
problem without notifying me, the caller of the
method. If I am in the middle of a deposit and the bank’s computer system fails, that might be my problem.
In that case, I want to be informed that my
deposit did not successfully go through. The deposit () method can tell me that the transaction was
unsuccessful
by throwing an exception back to me.

Syntax of throws keyword:

Void methodName () throws exceptionClassName {


...
}

Example for throws

class Excep13 {
void validate(int age) throws IOException {
if (age < 18)
throw new IOException("not valid");
else
[Link]("welcome to vote");
}
}

class Exception Handling {


public static void main(String args[]) throws IOException {
Excep13 obj = new Excep13();
[Link](13);
[Link] ("rest of the code...");
UNIT -II

}
}
Output:
(If age greater than 18)
welcome to vote
rest of the code...
(If age less than 18)
Exception in thread "main" [Link]: not valid
at [Link](Exception [Link])
at [Link](Exception [Link])

Which exception should we declare?


We should declare only checked exception, because:
Unchecked Exception: under your control so correct your code.
 Error: beyond your control e.g. you are unable to do anything if there occurs Virtual Machine
Error or Stack Overflow Error.
Note: Generally we declare only checked exception, but declaring unchecked exception will not give any
compilation error.

What is the advantage of throws keyword?


Checked Exception can be propagated (forwarded in call stack).
import [Link];

class Exception Handling {


void method3() throws IOException {
throw new IOException("device error");// checked exception
}

void method2() throws IOException {


method3();
}

void method1() {
try {
method2();
} catch (IOException exp) {
[Link]("exception handled");
}

public static void main(String args[]) {


ExceptionHandling obj = new ExceptionHandling();
obj.method1();
UNIT -II

[Link] ("normal flow...");


}
}

Output:
exception handled
normal flow...

In the above program following sequence happens


1. main method is a caller of method1()
2. method1() is a caller of method2()
3. method2() is a caller of method3()
4. method3() throws exception to caller, method2()
5. method2() throws exception to caller, method1()
6. method1() handles exception using try catch

Difference between throw and throws

Throw Throws

Throw is used to explicitly Throws is used to declare an exception.


throw an exception.
Syntax: Syntax:
throw <instance of any <Method signature> throws <exception class
exception class>; name>, <exception class name> ….

You can throw only one You can declare multiple exceptions.
exception.
UNIT -II

How to create custom exception in Java

If you are creating your own Exception then that is known as custom exception or user-defined exception

How to create user defined custom exception?

Following are the steps to create custom exception.


1. The class must extend any exception class.
2. If you want to create a checked exception extend class Exception.
3. If you want to create an unchecked exception extend class Runtime Exception.
Example:
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}

Types of Java Exceptions: Exceptions in java while programming is basically divided into two categories
Such as: I. Built-in Exceptions: These are the types
Of exception which can be caught using already existing java libraries? These exceptions are able to define
the error
Types of Java Exceptions: Exceptions in java while programming is basically divided into two categories
Such as:
I. Built-in Exceptions
II. User defined Exceptions
Built-in Exceptions: These are the types of exception which can be caught using already existing java
libraries. These exceptions are able to define the
error
Situation so that we can understand the reason of getting this error. It can be categorized into two broad
categories, i.e.
1. Checked Exception
2. Unchecked Exception
1 .Checked Exception:
Checked exceptions are called compile-time exceptions because these exceptions are
Checked at compile- time by the Compiler. The compiler ensures whether the programmer handles the
exception or not. The programmer
Should have to handle the exception; otherwise,
The system has shown a compilation error. The classes that directly inherit the Throwable class except
Runtime Exception and Error are known as checked exceptions.

For example: SQL Exception, IO Exception, Invocation Target Exception, and Class Not Found Exception.
2. Unchecked Exception:
The unchecked exceptions are just opposite to the checked exceptions. The compiler
Will not check these exceptions at
Compile time. In simple words, if a program throws an unchecked exception, and even if we didn't handle or
declare it, the program would not give a
Compilation error. Usually, it occurs when the user provides bad data during the interaction with the program
. The classes that inherit the Runtime
UNIT -II

Exceptions are known as unchecked exceptions For Example: programming bugs like Arithmetic Exception, Null
Pointer Exception, Array Index Out Of Bounds Exception, Logical Errors and using incorrect APIs.
II. User-Defined Exceptions: In java we can create our
Own exception class and throw that exception using throw keyword. An Exception that is defined by the user/
programmer is known as a user-defined or
Custom exception. This exception occurs whenever there is some customizable or errors done by user while
implementation and execution of program.
You can create your own exceptions in Java. Keep the following points in mind when writing your own
Exception classes. ▪All exceptions must be a child of
Throwable.
▪If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you
need to extend the Exception class.
▪If you want to write a runtime exception, you need to extend the Runtime Exception class.
Exception Description:
NullPointer ExceptionException is thrown when the JVM attempts to use an object reference that has not
been initialized or is null. Common causes include calling methods on null objects, accessing fields of null
Objects, or attempting to use null as an array.
Array Index Out Of Bounds Exception: Exception occurs when an application tries to access an array with
an index that is outside the valid range
(i.e., less than 0 or greater than or equal to the array's length).
Arithmetic Exception: Exception is thrown when an exceptional arithmetic condition has
Occurred. A common cause is division by zero.
Class Cast Exception: Exception is thrown when an application tries to cast an object to a subclass of which
it is not an instance. For example, casting an
Integer to a String.
Illegal Argument Exception: Exception is thrown to indicate that a method has been passed
an illegal or inappropriate argument.
For example, passing a negative value where only positive values are expected.
IllegalStateException
Exception is thrown when a method is invoked
at an illegal or inappropriate time. For example, calling next () on an iterator that has no more elements.
String Index out Of Bounds Exception Caused when a program attempts to access a nonexistent character
position in a string.
Number Format Exception: Exception is thrown when an attempt is made to convert a string to a numeric
type, but the string does not have an
appropriate format. For example, trying to parse "abc" into an integer. Unsupported Operation Exception is
thrown to indicate that the requested
UNIT -II

Operation is
Not supported by the object. For example, attempting to modify an un modifiable collection.
FileNotFoundException : Exception is thrown when an attempt to open a file denoted by a specified
Pathname has failed. It indicates that the file does not
Exist.
EOFException (End Of File Exception is thrown when an input operation has reached the Exception) end of
a file or stream unexpectedly.
Exception Exception is a general exception class that signals an I/O error has occurred. It is the superclass
of all the exceptions that can occur during I/O operations.
SQLException Exception is thrown when there is a database access error or other errors related to the
database operations. It is part of the
[Link] package.
No Such Element Exception Exception is thrown when one tries to access an element that is not present. For
example, calling next () on an empty iterator. Concurrent Modification Exception Exception thrown when a
collection is structurally modified while an iteration is in progress. For example, modifying a
List while iterating over it.
Out Of Memory Error Exception is a Error thrown when the JVM cannot allocate more memory. It can be
Due to memory leaks or insufficient heap space.
No Class Def. Found Error Exception is thrown if the JVM cannot find the definition of a class that was
Present during the compilation but is not available at runtime.
Class Not Found Exception Exception is thrown when an application tries to load a class through its name
but cannot find it. It typically occurs with
Dynamic class loading using reflection.
Custom exceptions:

If you are creating your own Exception then that is known as custom exception or user-defined exception.

How to create user defined custom exception?

Following are the steps to create custom exception.


1. The class must extend any exception class.
2. If you want to create a checked exception extend class Exception.
3. If you want to create an unchecked exception extend class Runtime Exception.
Example:
class InvalidAgeException extends Exception{
Invalid Age Exception(String s){
super(s);
}
}
Files and I/O Streams:

n Java, files and I/O streams are part of the [Link] and [Link] packages, which allow you to read from and

write to files, memory, sockets, and other data sources/sinks.

[Link] Class ([Link])

Used to represent file and directory pathnames in an abstract manner.


UNIT -II

Example:

Import [Link];

public class File Example {

Public static void main (String [] args) {


File file=new File ("[Link]");

If ([Link] ()) {
[Link] ("File exists");
} else {
[Link] ("File does not exist");
}

[Link] ("File name: " + [Link] ());


[Link] ("Absolute path: " + [Link] ());
}
}

[Link] Streams (Binary Data)

Use Input Stream and Output Stream for reading/writing binary data.

 File Input Stream – Reads bytes from a file.


 File Output Stream – Writes bytes to a file.

Example:

Import [Link];
Import [Link];
Import [Link];

Public class Byte Stream Example {


Public static void main(String[] args) throwsIOException {
File Input Stream in=new File Input Stream("[Link]");
File Output Stream out=new File Out put Stream ("[Link]");

int c;
while ((c = [Link]()) != -1) {
[Link](c);
}

[Link]();
[Link]();
}
}
UNIT -II

[Link] Streams (Text Data)

Use Reader and Writer classes for reading/writing character data.

 File Reader and File Writer are character-based equivalents of byte streams.

Example:

Import [Link] Reader;


Import [Link];
Import [Link];

Public class Char Stream Example {


Public static void main (String[] args) throwsIOException {
FileReaderreader=newFileReader ("[Link]");
FileWriterwriter=newFileWriter("[Link]");

Int c;
While ((c = reader. read ()) != -1) {
[Link](c);
}

Reader. close ();


[Link]();
}
}
[Link] Streams (Performance Enhancement)

Buffering is used to read/write data more efficiently.

 Buffered Reader, Buffered Writer


 Buffered Input Stream, Buffered Output Stream

Example (Buffered Reader):

Import [Link];
Import [Link];

Public class Buffered ReaderExample {


Public static void main (String [] args) throws Exception {
Buffered Reader br=new Buffered Reader(newFileReader("[Link]"));

String line;
While ((line = [Link]()) != null) {
[Link] (line);
}

[Link] ();
}
UNIT -II

}
[Link]-With-Resources (Auto-Close)

try (File Reader reader=newFileReader ("[Link]")) {


// use the reader
}
Streams in java:

Streams in java:
Stream is a flow of data from source to destination. A stream is a sequence of data that you can process
In a declarative and functional style.
streams provide a way to perform operations on data. In Java, Streams are a powerful abstraction for
performing input and output operations.
They allow reading/writing data from/to sources like files, memory, network sockets, or other
programs. TheStreamClasses
Java’s stream-based I/O is built upon four abstract classes: InputStream, OutputStream, Reader, and
[Link] OutputStreamare designed for byte streams. Reader and Writer are designed for
character streams. The byte stream classes and the character stream classes form separate hierarchies.

Types of Streams in Java

Java I/O streams are broadly categorized into:

1. Byte Streams ([Link])

 For binary data (images, videos, etc.)


 Base classes:
o Input Stream (for reading)
o Output Stream (for writing)

Common Byte Stream Classes:


Class Description

File Input Stream Reads bytes from a file

File Output Stream Writes bytes to a file

Buffered Input Stream Adds buffering to input

Buffered Output Stream Adds buffering to output

Data Input Stream Reads Java primitives from a stream

Data Output Stream Writes Java primitives to a stream


UNIT -II

2. Character Streams

 For text data (Unicode characters)


 Base classes:
o Reader (for reading characters)
o Writer (for writing characters)

Common Character Stream Classes:


Class Description

File Reader Reads characters from a file

File Writer Writes characters to a file

Buffered Reader Reads text efficiently, line-by-line

Buffered Writer Writes text efficiently

Print Writer Writes formatted text output

3. Buffered Streams

These wrap around other streams to increase efficiency.

 Input: Buffered Input Stream, Buffered Reader


 Output: Buffered Output Stream, Buffered Writer

4. Data Streams

Used for reading/writing Java primitive types in a machine-independent way.

 DataInputStream / DataOutputStream

Data Output Stream dos=new Data Output Stream (newFileOutputStream ("[Link]"));


[Link](42);
[Link]("Hello");
[Link]();

5. Object Streams

Used for reading/writing objects (serialization).

 ObjectInputStream / ObjectOutputStream

Object Output Stream os=newObjectOutputStream (newFileOutputStream ("[Link]"));


[Link] Object (my Object);
[Link] ();

6. Standard Streams

Predefined I/O streams:


UNIT -II

 [Link] → standard input (keyboard)


 System. out → standard output (console)
 System. Err → standard error

[Link]
|
---------------------
||
Byte Streams Character Streams
(Input Stream/(Reader/Writer)
Output Stream)
|
----------------------
||
File Streams Buffered Streams
Random Access File
Random Access File encapsulates a random-access file. It is not derived from Input
Stream or Output Stream. Instead, it implements the interfaces Data Input and Data
Output, which define the basic I/O methods. It also implements the Auto Closeable and
Closeable interfaces. Random Access File is special because it supports positioning
requests—that

is, you can position the file pointer with in the file. It has these two constructors:
Random Access File (File fileObj, String access) throws
File Not Found Exception
Random Access File (String filename, String access)
throws File Not Found Exception
In the first form, file Obj specifies the file to open as a File object. In the second form, the
name of the file is passed in filename. In both cases, access determines what type of file
access is permitted. If it is"r",then the file can be read, but not written. If it is"rw",then the
file is opened in read-write [Link] it is"rws",the file is opened for read-write operations and
UNIT -II

every change to the file’s data or metadata will be


immediately written to the physical device. If it is "rwd",
the file is opened for read-write operations and every
change to the file’s data will be immediately written to
the physical device.
Random Access File implements the standard input and
output methods, which you can use to read and write to
random access files. It also includes some additional methods.
One is setLength( ). It has this signature:
voidsetLength(longlen)throwsIOException
This method sets the length of the invoking file to that
specified by len. This method can be used to lengthen
or shorten a file. If the file is lengthened, the added
portion is undefined.
UNIT -II

UNIT III

PACKAGE:

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two forms

1. Built-in package 2. user-defined package.

✓ There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql

etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
UNIT -II

Defining a Package:

 To create a package is quite easy: simply include a package command as the


first statement in a Java source file. Any classes declared within that file will
belong to the specified package. The package
[Link]
ment,theclass names are put into the default package, which has no name.
 This is the general form of the
package statement: package
pkg;
 Here, pkg is the name of the package. For example ,the following statement creates
a package called
My Package:

Package My Package;
 More than one file can include the same package statement. The package
statement simply specifies to which package the classes defined in a file belong.
 You can create a hierarchy of packages. To do so, simply separate each package
name from the one above it by use of a period. The general form of a
multileveled package statement is shown here:
Package pkg1[.pkg2[.pkg3]];
UNIT -II
 ApackagehierarchymustbereflectedinthefilesystemofyourJavadevelopmentsystem.
For example, a
package
declared as
package
[Link]
age;

Finding Packages and CLASSPATH

 The Java run-time system looks for packages in three ways.


 First, by default, the Java run-time system uses the current working directory as
its starting point. Thus, if your package is in a subdirectory of the current
directory, it will be found.
 Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
 Third, you can use the -class path option with java and java c to specify the path to
your classes.
 When the second two options are used, the class path must not include My Pack,
itself. It must simply specify the path to My Pack. For example, in a Windows
environment, if the path to My Pack is
C:\MyPrograms\Java\MyPack
 Then the
class
path
to
My
Pack
is
C:\M
UNIT -II
yProg
rams\
Java
A
simpl
e
pack
age
exam
ple.
 Save the following file as
[Link] in a folder called pack.
Package pack;
Public class A

Public void msg ()

[Link] ("Hello") ;}
}

 Save the following file as [Link] in


a folder called my pack. Package
my pack;
Import pack.*;

Public class B

{
UNIT -II
Public static void
main (String
args[]){ A obj =
new A();

[Link]();
}

 Assume that pack and my pack folders are in the directory E:/java.
 compile:
E:/java>javac my pack/[Link]
Running:

E:/java>java my pack/BHello

PACKAGES AND MEMBER ACCESS:

 Javaprovidesmanylevelsofprotectiontoallowfine-
grainedcontroloverthevisibilityofvariablesand methods within classes,
subclasses, and packages.
 Classesandpackagesarebothmeansofencapsulatingandcontainingthenamespace
andscopeof variables and methods.
 [Link] acts
as containers for data and code.
 The class is Java’s smallest unit of abstraction.
 Becauseoftheinterplaybetweenclassesandpackages,Javaaddressesfourcategories
ofvisibilityfor class members:
• Subclasses in the same package

• Non-subclasses in the same package


UNIT -II
• Subclasses in different packages

• Classes that are neither in the same package nor subclasses

CLASSMEMBERACCESS
Private Default Protected Public
Member Member Member Memb
Visible within same class YES YES YES Y
Visible within same NO YES YES Y
package by subclass
Visible within same NO YES YES Y
package by non-subclass
Visible with in NO NO YES Y
different package by
subclass
Visible with in NO NO NO Y
different by non-subclass

A package access example:

The following is saved as [Link] in package p1

packagep1;

public class Protection{

Int n=1;

Pri
vat
e
int
n_p
UNIT -II
ri =
2;
pro
tect
ed
intn
_pr
o=3
;
pu
blic
int
n_p
ub
= 4;
pu
blic
Prot
ecti
on
() {

[Link]
("base
constructor");
[Link]
("n = " + n);
[Link]
("n_pri = " +
n_pri);
UNIT -II
[Link]
("n_pro = " +
n_pro);
[Link]
("n_pub="+n_pub
);
}

[Link]
vainpackag
ep1
package
p1;

Class Derived extends Protection

{
Derived()
{
[Link]
("derivedconstructo
r");
[Link]
("n = " + n);
//class only
//
[Link]
n ("n_pri = " +
UNIT -II
n_pri);
[Link]
n ("n_pro = " +
n_pro);
[Link]
n
("n_pub="+n_pub
);
}

SamePackage
.javainpacka
gep1 package
p1;

Class Same Package {

Same Package ()
{
Protection p = new Protection ();
[Link] ("same
package constructor");
[Link] ("n = " + p.n);
//class only
//
[Link]
("n_pri = " +
p.n_pri);
UNIT -II
[Link]
("n_pro = " +
p.n_pro);
[Link]
("n_pub="+p.n_pub
);
}

[Link]
npackagep2
package p2;

Class Protection2 extends


[Link] {

Protection2() {

[Link] ("derived other package constructor");


//class or package only
//[Link] ("n="+n);
//class only
//
[Link]
n ("n_pri = " +
n_pri);
[Link]
n ("n_pro = " +
n_pro);
UNIT -II
[Link]
n
("n_pub="+n_pub
);
}

Collections

In Java, Collections are a framework that provides architecture to store and manipulate a
group of objects. Java Collections Framework (JCF) is part of the [Link] package and
includes interfaces, implementations (classes), and algorithms to handle data.

Interfaces

o These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In
object-oriented languages, interfaces generally form hierarchy.
o All the core collection interfaces are generic.

Implementations

o These are the concrete implementations of the collection interfaces. In


essence, they are reusable data structures.
o All the classes in the collection framework implement the standard
interfaces and hence provide a standard way to work with different data structures.
o All the classes in the collection framework are data engines encapsulating
different data structures and have very high efficiency.
o All the classes encapsulate their own data structures. For example class
Linked List encapsulates linked list data structure, class Tree Set encapsulates tree
data structure, class Array List encapsulates array data structure, etc.
o Other classes and interfaces which are supporting collections in Java are:
UNIT -II
1. Collections. (Class)
2. Enumeration.(Interface)
3. Iterator.(Interface)
4. List Iterator.(Interface)
Java collection framework:
The java collections framework is a set of classes and interfaces with in the
[Link] package that provides an undefined architecture for representing and
manipulating collection of objects.
Benefits:
o Reduced Development Effort – All collection framework classes and
interfaces comes with almost all similar methods to iterate and manipulate the data.
So we can concentrate more on business logic rather than designing our collection
APIs.
o Increased Quality – All the data structures in collection framework are
having strong efficiency, using collection framework increases our program quality
rather than using any custom developed data structure.
o Increases performance - Collection framework has different flavor of data
structures and all the data structures have the common parent. So parent collection
class/interface can be used with various implementations. And we can change the
implementation at later point just by changing in single line. We can use any
implementation which well suits and tunes the application.
o Reduces the effort required to learn APIs by eliminating the need to
learn multiple ad hoc collection APIs each one from scratch.
o Reduces the effort required to design and implement APIs by
eliminating the need to produce ad hoc collections APIs. Designers and
implementers don't have to reinvent the wheel each time they create an API that
relies on collections; instead, they can use standard collection interfaces.
collections come in four basic flavors
UNIT -II

Collections come in four basic flavors

 Lists: Lists of things (classes that implement List).


 Sets: Set of unique things (classes that implement Set).
 Maps: Things with a unique ID (classes that implement Map).
 Queues: Things arranged by the order in which they are to be
processed.

But there are sub-flavors within those four flavors of collections

Java List

 Every item in this list is numbered with an index. By calling the list and
passing it a particular index value, a programmer can pull out any item placed into
it. Unlike counting things that exist in the real world, index variables always begin
with the number 0.
 List is an interface which extends Collection interface.
UNIT -II
 List allows duplicates.
 Array List allows duplicate and dissimilar object.
 All classes implementing List interface store values using index position.
 List has many concrete sub class implementations.
1. Vector
2. Array List
3. Linked List
4. Stack

Array List

 Array List uses array data structure internally to store the


elements.
 Array List stores values sequentially, but the values can be
accessed randomly.
 Array List can grow and shrink dynamically.
 Array List elements can be accessed randomly because it is
implementing Random Access marker interface.
 Elements in Array List are ordered by index(In the order as
inserted), but not sorted.
 Array List allows null.
 It provides very fast iteration. It is better to choose Array List over
Linked List when fast iteration is required.
 Insertion & deletion operation at a specified index in Array List is
time consuming and more complicated. It is better to choose Linked List when too
many insert and delete operations are being performed.
Linked List
 Linked List uses linked list data structure internally i.e. it uses
nodes.
UNIT -II
 Linked List is double linked.
 Linked List stores values non-contiguously or randomly.
 Linked List elements can be accessed sequentially only.
 It consumes lot of memory.
 The main advantage of Linked List is insertion and deletion
operation is very fast and can be performed without affecting other elements.
 Linked List can be used for implementing basic stack and queue
data structure.
 Iteration in Linked List is bit slow as compared to Array List.
 Values are accessed sequentially in Linked List, hence it is time
consuming.
 Linked List consumes more memory
 Values will be stored in the same order as inserted.
 Linked List elements cannot be accessed randomly.
 Linked List allows null.

Entire operations of Array List are same for Linked List, but

 It has extra method specified by Deque and Queue Interfaces.


 Methods Specified by Array List are absent.
 Has only two Constructors, constructor with initial capacity
argument is absent.

Vector

 Vector is same as Array List but Vector is synchronized and Array


List is not synchronized.
 Vector is a legacy class (Java 1.0) and represents array data
structure.
 Vector is re-engineered to fit into collection framework and is
implementing List interface and hence supports both 1.0 method and 1.2 methods.
UNIT -II
Stack

 Stack is a legacy class.


 It is also re-engineered like Vector to implement List interface.
Stack is a sub class of Vector.
 It is synchronized.
 It is generally used when we want to retrieve the elements of the
collection in FILO order (First in Last Out).

Java Queue

 Queue & Priority Queue were added in java 5 version.


 It stores the values in a heap (A heap is a new data structure and uses
binary tree).
 It allows only comparable objects.
 The elements should be always accessed by using poll() method while
iterating otherwise the values will be accessed in an undefined order.

Priority Queue

 Priority Queue stores values in an undefined order, but when the elements
are pulled from the queue it orders the values from the queue in a sorted order.
UNIT -II
Default is natural order or ascending order but if a custom comparator is used the
values can be ordered in descending order.
 Priority Queue is not synchronized. If a thread safe priority queue is
required use class Priority Blocking Queue.
 A basic queue always orders the values in the First in First Out order
(FIFO). A priority queue orders values based on priority.
 Priority Queue doesn’t allow null.
 Priority Queue allows duplicate values, but doesn’t allow dissimilar
objects.

Deque interface

 Deque interface and Array Deque class were added in java 6.


 Deque interface supports double ended queue.
 Deque also supports basic queue (FIFO) and stack (LIFO). Deque interface
has push() & pop() to support stack. It is more recommended to use Array Deque as
stack rather the legacy Stack class.

Array Deque class

 Array Deque class is likely to be faster than Stack when used as a stack,
and faster than Linked List when used as a queue.
 Array Deque is using array structure.
 Array Deque allows dissimilar values.
 Array Deque does not allow null values.
 Array Deque is not synchronized.
UNIT -II

Java Set
 Set models the mathematical set abstraction.
 Contains no methods other than those inherited from Collection.
 Two Set objects are equal if they contain the same elements.
 Lists are usually used to keep things in some kind of order, Lists allow you
to manually override the ordering of elements by adding or removing elements via
the element's index.
Set has 3 different implementations
1. Tree Set
2. Hash Set
3. Linked Hash Set

Tree Set

 Tree Set implements Sorted Set which is sub interface of Set.


 Elements in Tree Set are sorted by natural ascending order or custom
comparison rules.
 Null value is not allowed.
 Duplicates and dissimilar objects are not allowed.
 Elements cannot be access randomly.
 Tree Set uses tree data structure to store values.
UNIT -II

Java Map

 A map is an object that stores associations between keys and values,


or key/value pairs. Given a key, you can find its value. Both keys and values are
objects.
 The keys must be unique, but the values may be duplicated. Some maps
can accept a null key and null values, others cannot.
 The Map interface maps unique keys to values. A key is an object that we
use to retrieve a value at a later date. Given a key and a value, we can store the
value in a Map object. After the value is stored, we can retrieve it by using its key.
 Maps revolve around two basic operations: get ( ) and put ( ). To put a
value into a map, use put ( ), specifying the key and the value. To obtain a value,
call get ( ), passing the key as an argument. The value is returned.
 There are many different implementations of the Map interface.

1. Tree Map.
2. Hash Map.
UNIT -II
3. Linked Hash Map.
4. Hash table.
5. Properties

Tree Map

 Tree Map is implementing Sorted Map interface.


 Tree Map uses tree data structure to store the keys.
 The keys are stored in sorted order.
 Only similar types of keys are allowed.
 Different types of values are allowed.
 Duplicate keys are not allowed but duplicate values are allowed.
 Null keys are not allowed but null values.

Hash Map

 Hash Map uses hash table data structure to store the keys.
 Hash Map defines no any extra methods other than those inherited from Map Interface.
UNIT -II
Linked Hash Map

 Linked Hash Map store the keys in hash table data structure and
links them with double linked list.
 Linked Hash Map defines no any extra methods other than those
inherited from Map Interface.

Hash table

 Hash table can store key/value pairs.


 It uses hash table data structure to store the keys.
 Hash table is a legacy class (Java 1.0) and it was extending
Dictionary class.
 Hash table is re-engineered to fit into collection framework and is
implementing Map interface and hence supports both 1.0 methods and 1.2
methods.
 Hash table is same as Hash Map, but Hash table is synchronized
and Hash Map is not synchronized.
 Hash table is synchronized; multiple threads cannot access the
Hash table object concurrently. Only one thread can access the Hash table object at
a specific time.
 Since Hash table is synchronized, it has low performance than
Hash Map.
 Before to java 1.2 there was an interface called Enumeration to
visit the elements of Hash table. But now we have Iterator interface to visit the
elements of Hash table.
 The keys will be unordered or undefined order.
 Duplicate values are allowed.
 Different types of keys and values are allowed.
 Null keys and null values are not allowed.
UNIT -II

Sorting in Java : Sorting Rules


 We can sort the elements of a collection if and only if elements are
comparable. Which means class must have implemented Comparable interface, if
its objects are to be sorted. Objects of different or dissimilar type are not
comparable. We can sort only when the elements in the collection are of similar
type.
 We cannot sort when the elements in the collection are of dissimilar type.
 The sorting algorithm uses the comparison logic present in the
compareTo() method of Comparable interface or compare() method of Comparator
interface.
 To sort the elements in List (not Map, Set, Queue) java provides two
static methods which are present in Collections class.
1) Public static <T extends Comparable<? Super T>> void sort (List<T> list)
We can sort the elements of a collection if and only if elements are comparable. Which
means class must have implemented Comparable interface, if its objects are to be
sorted.
String class and Wrapper classes implements Comparable interface. So if we store
String/wrapper class elements they are comparable.
2) Public static <T> void sort (List<T> list, Comparator<? super T> c)
Here elements to be sorted need not to implement Comparator. We have to pass an
argument to the sort () method which should have implemented Comparator Interface.
Difference between Comparable and Comparator interfaces
comparable comparator
It is an interface in java. Lang package. It is an interface present in [Link] package
The Comparable Interface defines only The Comparator interface defines two
UNIT -II
one method. methods: compare ( ) and equals ( ).
Public int compareTo(Object obj)
We can sort the elements of a collection Here elements to be sorted need not to
if and only if elements are comparable. implement Comparator. We have to pass an
Which means class must have argument to the sort() method which should
implemented Comparable interface, if its have implemented Comparator Interface.
objects are to be sorted.
A comparable object can compare itself We can implement many sort sequences.
with another class.
Many built in classes like String, all It is generally implemented to compare 3rd
wrapper classes, Date, Calendar party classes or our user defined classes.
implement it.
UNIT -II

UNIT IV

MULTITHREADING

PROCESS AND THREAD: PROCESS:

1. It is an independent program in execution.


2. Process has its own memory space, code, data and system resources.
3. Process can contain multiple threads.
4. Communication between processes is complex.
THREAD:
1. It is a smaller unit of process.
2. Thread shares the same memory space with other threads of the same process.
3. Thread is lighter and more efficient than a process
4. It can be used to perform tasks concurrently.
PROCESS BASED AND THREAD BASED MULTITASKING:

Multi tasking is the ability of an operating system to run multiple tasks concurrently. There are two
main types.

1. Process based multi tasking


2. Thread based multi tasking
Process based multi tasking will run multiple programs at the same time. Each process is
independent and has its own memory space and also managed by the operating system.

E.g.: Running a java program, a web browser and a media player separately.

Thread based multitasking means a single program has multiple threads running concurrently. All
the threads share the same memory of the process. This is more light weight and efficient than
process based multi tasking.
UNIT -II
E.g.: A java server that handles multiple client requests simultaneously. Each request is
handled by a separate thread in the same program.

JAVA THREAD LIFE CYCLE:

In Java, a thread is a lightweight sub process, the smallest unit of processing. It is a separate path of
execution in a program, allowing multiple tasks to run concurrently.

A thread in Java is an instance of the [Link] class or an object that implements the
Runnable interface. It represents a single path of execution within a program.
UNIT -II

New state

When a thread instance/object is created, thread will be created and moved to “new” state.
Thread obj = new Thread (new MyRunnable ()); //thread will be created and moved to “new” state.

Runnable state

When start () method is called, thread moves to runnable state. A separate method call stack will be
created with run method being at the bottom of the call stack.
[Link] (); // new moves to runnable state
A thread can also return to the “runnable state” after coming back from a running, sleeping, waiting
or blocked state.

Running state

In running state, thread will be running, in fact code present inside run () method will be
executing. A thread can move out of the “running state” to runnable, non-runnable or dead state for
various reasons. Also we can move running thread to other state explicitly by calling yield (), sleep
(), wait (), join or stop () method etc.

Non runnable state (Sleeping state, Waiting state and Blocked state)

A non-runnable thread is a paused thread because of certain reasons like unavailability of resources,
waiting for another thread to finish, user explicitly paused etc...
When this non runnable thread is ready for re-run it will move to runnable state, but not to running
state.
We have three types of non-runnable threads
1. Sleeping state: A thread moves into the “sleeping state “when sleep () is called on
a running thread.
2. Waiting state: A thread moves into the “waiting state” when wait() is called on a
running Thread
3. Blocked state: A thread moves into the “blocked state” when join () is called or
when a resource is not available.
UNIT -II
Dead state

When run method execution is completes, thread moves to dead state.


We can also call stop () or destroy () method explicitly to move a running thread into “dead state”
but the methods have been deprecated.

CREATING THREADS

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.

1. By extending Thread class


The java contains a built-in class Thread inside the [Link] package. The Thread class
contains all the methods that are related to the threads.

To create a thread using Thread class, follow the step given below.
Step-1: Create a class as a child of Thread class. That means, create a class that extends Thread
class.
Step-2: Override the run ( ) method with the code that is to be executed by the thread.
The run ( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main () method.
Step-4: Call the start () method on the object created in the above step.

THREAD PRIORITIES

 In a java programming language, every thread has a property called priority.

 Priorities are represented by a number between 1 and 10. In most cases, thread
scheduler schedules the threads according to their priority (known as preemptive
scheduling).
 The thread with more priority allocates the processor first.

 But it is not guaranteed because it depends on JVM specification that which scheduling it
chooses.
UNIT -II
Three constants defined in Thread class:

1. MIN_PRIORITY

2. NORM_PRIORITY

3. 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.
 The java programming language Thread class provides two methods set Priority (int),
and get Priority ( ) to handle thread priorities.

SetPriority () method

The set Priority () method of Thread class used to set the priority of a thread.

It takes an integer range from 1to10 as an argument and returns nothing (void).

Example

[Link] (4);

[Link]
ority (MAX_PRIORITY);

Get Priority () method

The get Priority ( ) method of Thread class used to access the priority
of a thread. It does not take any argument and returns name of the
thread as String.
Inter thread communication:

INTER THREAD COMMUNICATION

 Inter thread communication is the concept where two or more threads communicate to
solve the problem of polling.
 In java, polling is the situation to check some condition repeatedly, to take appropriate
action, once the condition is true.
 That means, in inter-thread communication, a thread waits until a condition becomes
true such that other threads can execute its task.
UNIT -II
 The inter-thread communication allows the synchronized threads to communicate with
each other.
Java provides the following methods to achieve inter thread communication.

Method Description

Void wait ( ) It makes the current thread to pause its execution until other
thread in the same monitor calls notify ( )

Void notify () It wakes up the thread that called wait () on the same object.

Void notify All () It wakes up all the threads that called wait () on the same object.

JDBC

Below concepts are mandatory prerequisites concepts to learn JDBC.


1. Java programming language.
2. RDBMS (Database)
3. SQL

Relational Data Base Management System (RDBMS)

 A relational database management system (RDBMS) is an implementation of


database management system (DBMS) or software that is used to maintain database.
 In RDBMS data will be stored in many tables and all the tables will be related with
each other with the help of Primary Key and Foreign Key.
 RDBMS database use SQL (Structured Query Language) to communicate with the
system.

SQL

SQL stands for Structured Query Language in DBMS and is used to communicate with database.
SQL is a standard proposed by ANSI.

Types of JDBC Drivers


UNIT -II

Generally driver means software which enables any external device to interact with
computer. JDBC Driver is software that enables java application to interact with the database.
There are four types of JDBC drivers in use:

 Type 1: JDBC-ODBC Bridge driver


 Type 2: partial Java driver: Native-API driver
 Type 3: pure Java driver with database middleware: Network Protocol driver
 Type 4: pure Java driver directly to database: Thin driver

JDBC-ODBC bridge driver

ODBC drives acts as a bridge between JDBC and database. The JDBC-ODBC bridge driver converts
database calls into the ODBC calls. Now ODBC driver connects to the database.

Native-API driver

These drivers are typically provided by the database vendors. Native-API acts as a bride between
JDBC and database. Native–API driver converts database calls into the native C/C++ API calls. Now
Native API connects to the database.

Network Protocol driver


UNIT -II
Middleware server acts a bridge between JDBC and database. This Middleware server converts
JDBC calls to database understandable calls.

Thin driver

The thin driver converts JDBC calls directly into database understandable calls. That is why it is
known as thin driver. It is completely written in Java language.

Jdbc architecture:

JDBC Architecture refers to the design and components that enable Java applications to interact
with relational databases using the Java Database Connectivity (JDBC) API. JDBC acts as a
bridge between Java code and database systems.

JDBC (Java Database Connectivity) is a Java API that enables Java applications to interact with
databases. It includes a set of classes and interfaces in the [Link] and [Link] packages.
UNIT -II
Here are the most important JDBC interfaces:

Interface Description

Interface implemented by database vendors to register and connect their


Driver
database with Java applications.

Connection Represents a connection to a database.

Statement Used to execute static SQL queries (without parameters).

PreparedStatement Used to execute precompiled SQL queries with parameters.

Callable Statement Used to execute stored procedures.

Result Set Represents the result set from SQL queries.

ResultSetMetaData Provides metadata (column count, types, etc.) about a Result Set.

Database Meta Data Provides metadata about the database (tables, supported features, etc.).

Data Source (in Used for establishing connections via connection pooling (more advanced
[Link]) than Driver Manager).

More flexible and disconnected Result Set-like object (e.g., JdbcRowSet,


Row Set
CachedRowSet).

🔹 Core JDBC Classes

Here are the commonly used JDBC classes:

Class Description

Driver Manages a list of database drivers. Used to establish a connection with a database.
UNIT -II
Class Description

Manager

Types Contains constants for SQL types (e.g., Types. INTEGER, [Link]).

Date, Time,
Classes used to represent SQL date/time values.
Timestamp

Used to handle database warnings (not exceptions).

Developing jdbc application

Developing a JDBC (Java Database Connectivity) application involves a series of


steps to connect a Java application to a relational database, execute queries, and handle
results. Here's a basic outline of the steps:

1. Import JDBC Packages


Import [Link].*;

2. Load and Register JDBC Driver

This step loads the database driver class

[Link]("[Link]");

For newer JDBC versions, loading the driver explicitly might not be required.

3. Establish a Connection

Use [Link]() to connect to the database


UNIT -II
Class Description

Connection con = [Link](


"jdbc:mysql://localhost:3306/yourDatabaseName", "username", "password");

4. Create a Statement

Use Statement, Prepared Statement, or Callable Statement depending on your use case.

Statement stmt = con. create Statement();

5. Execute the Query

You can use execute Query() for SELECT and execute Update() for INSERT,
UPDATE, DELETE.

Result Set rs = [Link]("SELECT * FROM your_table_name");

6. Process the Results

Iterate over the Result Set to read the data.

while ([Link]()) {
[Link]([Link]("column_name"));
}

7. Close the Connection

Always close the resources to avoid memory leaks.

[Link]();
[Link]();
[Link]();
UNIT -II
Class Description

✅Summary of JDBC Steps:

1. Import JDBC packages


2. Load and register the driver
3. Establish a connection
4. Create a statement
5. Execute the query
6. Process the results
7. Close the connection
UNIT -II

UNIT V

GUI PROGRAMMING WITH SWING

INTRODUCTION:

Java Swing is a graphical user interface (GUI) toolkit that is part of the Java Foundation
Classes (JFC). It provides a rich set of components for building desktop applications with a
graphical interface.

Key Concepts of Java Swing:

Light weight Components:

Unlike AWT (Abstract Window Toolkit) components, which rely on native operating
system peers, Swing components are "lightweight" and rendered entirely in Java, making
them platform-independent and more flexible in terms of look and feel.

Pluggable Look and Feel (PLaF):

Swing allows you to change the visual appearance of your application without modifying
the code, enabling different "looks" (e.g., Metal, Nimbus, or OS-specific looks).

Components and Containers:

Swing applications are built using a hierarchy of components and containers.

Components: These are the individual interactive elements like buttons (J Button), text fie
fields (J Text Field), labels (J Label), checkboxes (J Check Box), etc.

Containers: These are components that can hold other components, such as frames
(JFrame), panels (JPanel), and dialogs (JDialog). JFrame is typically the top-level window
for a Swing application.
ayout Managers:

These control the arrangement and sizing of components within a container. Common
layout managers include Border Layout, Flow Layout, Grid Layout, and GridBagLayout.
UNIT -II
vent Handling:
Swing components can respond to user interactions (events) like mouse clicks, key
presses, or window closing. This is achieved by attaching "event listeners" to components,
which execute specific code when an event occurs.
Basic Structure of a Simple Swing Application:

Create a JFrame: This serves as the main application window.

Create Components: Instantiate Swing components like JButton, JLabel, etc.

Add Components to a Container: Place the components within a JPanel or directly onto
the JFrame's content pane.

Set Layout Manager: Arrange the components within the container using a chosen layout
manager.

Add Event Listeners: Implement event handling for interactive components.

Set Frame Properties: Configure the frame's size, title, default close operation, and make
it visible.
Limitations of AWT:
AWT: AWT stands for Abstract Window Toolkit, which is an API for creating graphical
user interface (GUI) or Window-based applications in java. AWT provides various
components like buttons, labels, text fields, etc. that can be used as objects in java program.

AWT Program in Java

AWT stands for Abstract window toolkit is an Application programming interface (API) for
creating Graphical User Interface (GUI) in Java. It allows Java programmers to develop
window-based applications.

AWT provides various components like button, label, checkbox, etc. used as objects inside
a Java Program. AWT components use the resources of the operating system, i.e., they are
platform-dependent, which means, component's view can be changed according to the view
UNIT -II
of the operating system. The classes for AWT are provided by the [Link] package for
various AWT components.

The following image represents the hierarchy for Java AWT.

Component Class

The component class stands at the top of the AWT hierarchy, is an abstract class that
contains all the properties of the component visible on the screen. The Component object
contains information about the currently selected foreground and background color. It also
has information about the currently selected text color.
UNIT -II
Container

The container is a component that contains other components like button, text field, label,
etc. However, it is a subclass of the Component class.

Panel

The panel can be defined as a container that can be used to hold other components.
However, it doesn't contain the title bar, menu bar, or border.

Window

A window can be defined as a container that doesn't contain any border or menu bar. It
creates a top-level view. However, we must have a frame, dialog, or another window for
creating a window.

Frame

The frame is a subclass of Window. It can be defined as a container with components like
button, text field, label, etc. In other words, AWT applications are mostly created using
frame container.

Java AWT Example

Consider the following simple example of Java AWT in which we have shown an awt
component button by setting its placement and window frame size.

Import [Link].*;
Public class AwtProgram1 {
public AwtProgram1()
{
Frame f = new Frame();
Button btn=new Button("Hello World");
UNIT -II
[Link](80, 80, 100, 50);
[Link] (btn); //adding a new Button.
[Link] (300, 250); //setting size.
0. [Link] ("Java Point"); //setting title.
1. [Link] (null); //set default layout for frame.
2. [Link] (true); //set frame visibility true.
3. }
4. public static void main(String[] args) {
5. // TODO Auto-generated method stub
6. AwtProgram1 awt = new AwtProgram1 (); //creating a frame.
7. }
8. }

Output:

The limitations of AWT (Abstract Window Toolkit) in Java include:

Platform Dependence:

AWT components are "heavyweight," meaning they rely on the native operating system's
GUI components. This leads to inconsistencies in look and behavior across different
platforms, contradicting Java's "write once, run anywhere" philosophy.
UNIT -II
Limited Component Set:

AWT offers a relatively small set of GUI components compared to later frameworks like
Swing or JavaFX. Essential components like tables and trees are not natively available.

Poor Customization:

The ability to customize the appearance and behavior of AWT components is limited due
to their reliance on native peer components.

Performance Issues:

AWT can exhibit slower rendering and event handling compared to lightweight GUI
toolkits, especially on certain platforms.

Lack of Advanced Features:

AWT does not inherently support advanced UI features such as drag-and-drop, rich text
editing, or complex component arrangements without significant custom coding.

Complex Layout Management:

While AWT provides layout managers, achieving complex and flexible component
arrangements can be challenging and require intricate configurations.

Heavy weight Nature:

Each AWT component has a corresponding native peer, which consumes system resources
and can contribute to higher memory usage.

Limited Extensibility:

Due to its platform dependence and reliance on native components, extending AWT
components or creating highly customized components is often difficult.

MVC Architecture in Java


The Model-View-Controller (MVC) is a well-known design pattern in the web
development field. It is way to organize our code. It specifies that a program or application
shall consist of data model, presentation information and control information.
UNIT -II
The MVC pattern architecture consists of three layers:

o Model: It represents the business layer of application. It is an object to carry the


data that can also contain the logic to update controller if data is changed.

o View: It represents the presentation layer of application. It is used to visualize the


data that the model contains.

o Controller: It works on both the model and view. It is used to manage the flow of
application, i.e. data flow in the model object and to update the view whenever data
is changed.

In Java Programming, the Model contains the simple Java classes, the View used to display
the data and the Controller contains the servlets. Due to this separation the user requests are
processed as follows:

1. A client (browser) sends a request to the controller on the server side, for a page.

2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.

4. Now the result is sent back to the browser (client) by the view.
UNIT -II
Advantages of MVC Architecture

The advantages of MVC architecture are as follows:

The components are easy to maintain because there is less dependency.

o A model can be reused by multiple views that provides reusability of code.

o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require to deal
with massive code.

 Codes are easy to maintain and they can be extended easily.


 The MVC model component can be tested separately.
 The components of MVC can be developed simultaneously.
 It reduces complexity by dividing an application into three units. Model, view, and
controller.
 It supports Test Driven Development (TDD).
 It works well for Web apps that are supported by large teams of web designers and
developers.
 This architecture helps to test components independently as all classes and objects are
independent of each other

o Search Engine Optimization (SEO) Friendly

Disadvantages of MVC:
 It is difficult to read, change, test, and reuse this model
 It is not suitable for building small applications.
 The inefficiency of data access in view.
 Increased complexity and Inefficiency of data
UNIT -II
Example:

[Link].*;

// Driver Class

Class Submit Button extends Frame {

// main function

Public static void main(String[] args)

{ // create instance of frame with label

Frame frame = new Frame("Submit form");

// create instance of button with label

Button button = new Button("Submit");

// set the position for the button in frame

[Link](40, 130, 70, 20);

// adding button to the frame

[Link](button);
UNIT -II

// setting size for the frame

[Link](500, 500);

// setting layout for the frame

[Link](null);

// visibility of frame to display the output\

// without this output will be blank

[Link](true);

}}

We can run it by the following commands:

Output:
UNIT -II
UNIT -II
UNIT -II
Event Handling in Java
An event can be defined as changing the state of an object or behavior by performing
actions. Actions can be a button click, cursor movement, keypress through keyboard or
page scrolling, etc.
The [Link] package can be used to provide various event classes.

Classification of Events
 Foreground Events
 Background Events


 Types of Events

1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground
events are generated due to interaction by the user on components in Graphic User
Interface (GUI). Interactions are nothing but clicking on a button, scrolling the scroll bar,
cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background
events. Examples of these events are operating system failures/interrupts, operation
completion, etc.

Event Handling

It is a mechanism to control the events and to decide what should happen after an
event occur. To handle the events, Java follows the Delegation Event model.
UNIT -II
Delegation Event model
 It has Sources and Listeners.

Delegation Event Model

 Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to
generate events.
 Listeners: Listeners are used for handling the events generated from the source. Each
of these listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.

Registering the Source With Listener


Different Classes provide different registration methods.
Syntax:
AddTypeListener ()
Where Type represents the type of event.
Example 1: For Key Event we use add Key Listener () to register.
Example 2: that For Action Event we use add Action Listener() to register.

Event Classes in Java

Event Class Listener Interface Description

An event that indicates that a component-


Action Event Action Listener
defined action occurred like a button click or
UNIT -II
Event Class Listener Interface Description

selecting an item from the menu-item list.

Adjustment Adjustment The adjustment event is emitted by an


Event Listener Adjustable object like Scrollbar.

An event that indicates that a component


Component Component
moved, the size changed or changed its
Event Listener
visibility.

When a component is added to a container


Container
Container Listener (or) removed from it, then this event is
Event
generated by a container object.

These are focus-related events, which include


Focus Event Focus Listener
focus, focus In, focus out, and blur.

An event that indicates whether an item was


Item Event Item Listener
selected or not.

An event that occurs due to a sequence of key


Key Event Key Listener
presses on the keyboard.

Mouse Listener
The events that occur due to the user
Mouse Event &Mouse Motion
interaction with the mouse (Pointing Device).
Listener
UNIT -II
Event Class Listener Interface Description

Mouse Wheel Mouse Wheel An event that specifies that the mouse wheel
Event Listener was rotated in a component.

An event that occurs when an object’s text


Text Event Text Listener
changes.

Window An event which indicates whether a window


Window Listener
Event has changed its status or not.

Note: As Interfaces contains abstract methods which need to implemented by the


registered class to handle events.
Different interfaces consist of different methods which are specified below.

Listener Interface Methods

Action Listener  Action Performed()

Adjustment Listener  Adjustment Value Changed()

 Component Resized()
 Component Shown()
Component Listener
 Component Moved()
 Component Hidden()

 Component Added()
Container Listener
 Component Removed()
UNIT -II
Listener Interface Methods

 Focus Gained()
Focus Listener
 Focus Lost()

Item Listener  Item State Changed()

 Key Typed()
Key Listener  Key Pressed()
 Key Released()

 Mouse Pressed()
 Mouse Clicked()
Mouse Listener  Mouse Entered()
 Mouse Exited()
 Mouse Released()

 Mouse Moved()
Mouse Motion Listener
 Mouse Dragged()

Mouse Wheel Listener  mouse Wheel Moved()

Text Listener  text Changed()

 window Activated()
 window Deactivated()
Window Listener
 window Opened()
 window Closed()
UNIT -II
Listener Interface Methods

 window Closing()
 window Iconified()
 window De iconified()

Code-Approaches
The three approaches for performing event handling are by placing the event handling
code in one of the below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class
Note: Use any IDE or install JDK to run the code, Online compiler may throw errors due
to the unavailability of some packages.

Event Handling Within Class

// Java program to demonstrate the event handling within the class

[Link].*;

Import [Link]. event.*;

Class GFG Top extends Frame implements Action Listener {

Text Field text Field;

GFG Top()
UNIT -II

// Component Creation

Text Field = new Text Field();

// set Bounds method is used to provide

// position and size of the component

Text Field. Set Bounds(60, 50, 180, 25);

Button button = new Button("click Here");

Button. set Bounds(100, 120, 80, 30);

// Registering component with listener

// this refers to current instance

[Link](this);

// add Components

add(text Field);

add(button);
UNIT -II

// set visibility

Set Visible(true);

// implementing method of action Listener

Public void action Performed(Action Event e)

// Setting text to field

Text Field .set Text("GFG!");

Public static void main(String[] args)

New GFG Top();

}
UNIT -II
Output

After Clicking, the text field value is set to GFG!

Explanation
1. Firstly extend the class with the applet and implement the respective listener.
2. Create Text-Field and Button components.
3. Registered the button component with respective event. I.e. Action Event by add
Action Listener ().
4. In the end, implement the abstract method.

Event Handling by Other Class

// Java program to demonstrate the event handling by the other class

[Link].*;

Import [Link]. Event.*;

classGFG1 extends Frame {


UNIT -II

Text Field text Field;

GFG2()

// Component Creation

Text Field = new Text Field();

// set Bounds method is used to provide

// position and size of component

Text Field. Set Bounds(60, 50, 180, 25);

Button button = new Button("click Here");

Button. set Bounds(100, 120, 80, 30);

Other other = new Other(this);

// Registering component with listener

// Passing other class as reference

[Link](other);
UNIT -II

// add Components

add(text Field);

add(button);

// set visibility

set Visible(true);

Public static void main(String[] args)

newGFG2();

/// import necessary packages

Import [Link].*;
UNIT -II

// implements the listener interface

Class Other implements Action Listener {

GFG2 gfgObj;

Other(GFG1 gfgObj) {

[Link] = gfgObj;

Public void action Performed(Action Event e)

// setting text from different class

[Link]("Using Different Classes");

}}
UNIT -II
Output

Handling event from different class

Event Handling By Anonymous Class

// Java program to demonstrate the event handling by the anonymous class

[Link].*;

[Link].*;

classGFG3 extends Frame {

Text Field text Field;

GFG3()

// Component Creation
UNIT -II

Text Field = new Text Field();

// set Bounds method is used to provide

// position and size of component

Text [Link](60, 50, 180, 25);

Button button = new Button("click Here");

[Link](100, 120, 80, 30);

// Registering component with listener anonymously

[Link](newActionListener() {

public void action Performed(Action Event e)

// Setting text to field

Text [Link]("Anonymous");

});
UNIT -II

// add Components

add(text Field);

add(button);

//make size viewable

Set Size(300,300);

// set visibility

Set Visible(true);

Public static void main(String[] args)

newGFG3();

}
UNIT -II
Output

Handling anonymously

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods

For registering the component with the Listener, many classes provide the registration
methods. For example:

o Button
o public void add Action Listener(Action Listener a){}

o Menu Item
o public void add Action Listener(Action Listener a){}

o Text Field
o public void add Action Listener(Action Listener a){}
o public void add Text Listener(Text Listener a){}
UNIT -II
o Text Area
o public void add Text Listener(Text Listener a){}

o Checkbox
o public void add Item Listener (Item Listener a){}

o Choice
o public void add Item Listener(Item Listener a){}

o List
o public void add Action Listener(Action Listener a){}
o public void add Item Listener(Item Listener a){}

Delegation Event Model in Java

The Delegation Event model is defined to handle events in GUI programming languages.
The GUI stands for Graphical User Interface, where a user graphically/visually interacts
with the system.

The GUI programming is inherently event-driven; whenever a user initiates an activity such
as a mouse activity, clicks, scrolling, etc., each is known as an event that is mapped to a
code to respond to functionality to the user. This is known as event handling.

In this section, we will discuss event processing and how to implement the delegation event
model in Java. We will also discuss the different components of an Event Model.

Event Processing in Java

Java support event processing since Java 1.0. It provides support for AWT ( Abstract
Window Toolkit), which is an API used to develop the Desktop application. In Java 1.0, the
AWT was based on inheritance. To catch and process GUI events for a program, it should
hold subclass GUI components and override action() or handle Event() methods. The below
image demonstrates the event processing.
UNIT -II

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
UNIT -II
o Events Sources

o Events Listeners

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:

public void add Type Listener (Type Listener 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 add Key
Listener (). For the mouse event listener, the method will be called as add Mouse Motion
Listener (). 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
UNIT -II
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:

public void addTypeListener(TypeListener e2) throws [Link]


n

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.

public void remove Type Listener(Type Listener 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 remove Key Listener() 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.
UNIT -II
The methods that deal with the events are defined in a set of interfaces. These interfaces can
be found in the [Link] 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.

The Delegation Model

The Delegation Model is available in Java since Java 1.1. it provides a new delegation-
based event model using AWT to resolve the event problems. It provides a convenient
mechanism to support complex Java programs.

Design Goals

The design goals of the event delegation model are as following:

o It is easy to learn and implement

o It supports a clean separation between application and GUI code.


o It provides robust event handling program code which is less error-prone (strong
compile-time checking)

o It is Flexible, can enable different types of application models for event flow and
propagation.

o It enables run-time discovery of both the component-generated events as well as


observable events.

o It provides support for the backward binary compatibility with the previous model.

Let's implement it with an example:

Java Program to Implement the Event Deligation Model

The below is a Java program to handle events implementing the event deligation model:
UNIT -II
[Link]:

Import [Link].*;
Import [Link].*;

public class Test App {


public void search() {
// For searching
[Link] ("Searching...");
}
public void sort() {
0. // for sorting
1. [Link] ("Sorting....");
2. }
3.
4. static public void main(String args[]) {
5. Test App app = new TestApp();
6. GUI gui = new GUI(app);
7. }
8. }
9.
0. class Command implements Action Listener {
1. static final int SEARCH = 0;
2. static final int SORT = 1;
3. int id;
4. Test App app;
5.
6. public Command(int id, Test App app) {
7. [Link] = id;
8. [Link] = app;
UNIT -II
9. }
0.
1. public void action Performed(Action Event e) {
2. switch(id) {
3. case SEARCH:
4. app. search();
5. break;
6. case SORT:
7. app. sort();
8. break;
9. }
0. }
1. }
2.
3. class GUI {
4.
5. public GUI(Test App app) {
6. Frame f = new Frame();
7. [Link] Layout(new Flow Layout());
8.
9. Command search Cmd = new Command (Command. SEARCH, app);
0. Command sort Cmd = new Command (Command. SORT, app);
1.
2. Button b;
3. [Link](b = new Button("Search"));
4. [Link] Listener(search Cmd);
5. [Link](b = new Button("Sort"));
6. [Link](sortCmd);
7.
8. List l;
UNIT -II
9. [Link](l = new List());
0. [Link]("Alphabetical");
1. [Link]("Chronological");
2. l. add Action Listener(sort Cmd);
3. [Link]();
4.
5. [Link]();
6. }
7. }

Output:

Java Mouse Listener Interface

The Java Mouse Listener is notified whenever you change the state of mouse. It is notified
against Mouse Event. The Mouse Listener interface is found in [Link] package. It
has five methods.

Methods of Mouse Listener interface

The signature of 5 methods found in Mouse Listener interface are given below:

public abstract void mouse Clicked(Mouse Event e);


public abstract void mouse Entered(Mouse Event e);
public abstract void mouse Exited(Mouse Event e);
public abstract void mouse Pressed(Mouse Event e);
UNIT -II
public abstract void mouse Released(Mouse Event e);

Java Mouse Listener Example

Import [Link].*;
Import [Link].*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
Mouse Listener Example(){
Add Mouse Listener(this);

l=new Label();
l. set Bounds(20,50,100,20);
0. add(l);
1. Set Size(300,300);
2. Set Layout(null);
3. Set Visible(true);
4. }
5. public void mouse Clicked(Mouse Event e) {
6. l. set Text("Mouse Clicked");
7. }
8. public void mouse Entered(Mouse Event e) {
9. l. set Text("Mouse Entered");
0. }
1. public void mouse Exited(Mouse Event e) {
2. l. set Text("Mouse Exited");
3. }
4. public void mouse Pressed(Mouse Event e) {
5. l. set Text("Mouse Pressed");
6. }
7. public void mouse Released(Mouse Event e) {
UNIT -II
8. L .set Text("Mouse Released");
9. }
0. public static void main(String[] args) {
1. new Mouse Listener Example();
2. }
3. }

Output:

Java Mouse Motion Listener Interface

The Java Mouse Motion Listener is notified whenever you move or drag mouse. It is
notified against Mouse Event. The Mouse Motion Listener interface is found in
[Link] package. It has two methods.

Methods of Mouse Motion Listener interface

The signature of 2 methods found in MouseMotionListener interface is given below:

public abstract void mouse Dragged(Mouse Event e);


public abstract void mouse Moved(Mouse Event e);

Java Mouse Motion Listener Example

Import [Link].*;
Import [Link].*;
UNIT -II
public class MouseMotionListenerExample extends Frame implements MouseMotionList
ener{
Mouse Motion Listener Example(){
addMouseMotionListener(this);

Set Size(300,300);
Set Layout(null);
Set Visible(true);
0. }
1. public void mouse Dragged(Mouse Event e) {
2. Graphics g=get Graphics();
3. [Link] Color (Color. BLUE);
4. [Link]([Link](),[Link](),20,20);
5. }
6. public void mouse Moved(Mouse Event e) {}
7.
8. public static void main(String[] args) {
9. new Mouse Motion Listener Example();
0. }
1. }

Output:
UNIT -II

Mouse Listener and Mouse Motion Listener in Java


Mouse Listener and Mouse Motion Listener is an interface in [Link] package.
Mouse events
are of two types. Mouse Listener handles the events when the mouse is not in motion.
While Mouse Motion Listener
handles the events when mouse is in motion.
There are five types of events that Mouse Listener can generate. There are five abstract
functions that represent these five events.
The abstract functions are:

1. void mouse Released(Mouse Event e) : Mouse key is released


2. void mouse Clicked(Mouse Event e) : Mouse key is pressed/released
3. void mouse Exited(Mouse Event e) : Mouse exited the component
4. void mouse Entered(Mouse Event e) : Mouse entered the component
5. void mouse pressed(Mouse Event e) : Mouse key is pressed
There are two types of events that Mouse Motion Listener can generate. There are two
abstract functions that represent these five events.
UNIT -II
The abstract functions are:

1. Void mouse Dragged (Mouse Event e) : Invoked when a mouse button is pressed in
the component and dragged. Events are passed until the user releases the mouse
button.
2. Void mouse Moved (Mouse Event e) : invoked when the mouse cursor is moved
from one point to another within the component, without pressing any mouse buttons.

Java Key Listener Interface

The Java Key Listener is notified whenever you change the state of key. It is notified
against Key Event. The Key Listener interface is found in [Link] package, and it
has three methods.

Interface declaration

Following is the declaration for [Link] interface:

public interface Key Listener extends Event Listener


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:


o It assists the unrelated classes to work combined.

o It provides ways to use classes in different ways.


o It increases the transparency of classes.

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


o It provides a pluggable kit for developing an application.
UNIT -II
o It increases the reusability of the class.

The adapter classes are found in [Link],


[Link] and [Link] packages. The Adapter classes with their
corresponding listener interfaces are given below.

[Link] Adapter classes

Adapter class Listener interface

Window Adapter Window Listener

Key Adapter Key Listener

Mouse Adapter Mouse Listener

Mouse Motion Adapter Mouse Motion Listener

Focus Adapter Focus Listener

Component Adapter Component Listener

Container Adapter Container Listener

Hierarchy Bounds Adapter Hierarchy Bounds Listener

[Link] Adapter classes

Adapter class Listener interface

Drag Source Adapter Drag Source Listener


UNIT -II
Drag Target Adapter Drag Target Listener

[Link] Adapter classes

Adapter class Listener interface

Mouse Input Adapter Mouse Input Listener

Internal Frame Adapter Internal Frame Listener

Java Window Adapter Example

In the following example, we are implementing the Window Adapter class of AWT and one
its methods window Closing() to close the frame window.

[Link]

Backward Skip 10sPlay VideoForward Skip 10s

// importing the necessary libraries


Import [Link].*;
Import [Link].*;

public class Adapter Example {


// object of Frame
Frame f;
// class constructor
Adapter Example() {
0. // creating a frame with the title
1. f = new Frame ("Window Adapter");
2. // adding the Window Listener to the frame
UNIT -II
3. // overriding the window Closing() method
4. [Link] Listener (new Window Adapter() {
5. public void window Closing (Window Event e) {
6. [Link]();
7. }
8. });
9. // setting the size, layout and
0. [Link] Size (400, 400);
1. [Link] Layout (null);
2. [Link] Visible (true);
3. }
4.
5. // main method
6. public static void main(String[] args) {
7. new Adapter Example();
8. }
9. }

Output:
UNIT -II
Java Mouse Adapter Example

In the following example, we are implementing the Mouse Adapter class. The Mouse
Listener interface is added into the frame to listen the mouse event in the frame.

[Link]

// importing the necessary libraries


Import [Link].*;
Import [Link].*;

// class which inherits the Mouse Adapter class


public class Mouse Adapter Example extends Mouse Adapter {
// object of Frame class
Frame f;
// class constructor
0. Mouse Adapter Example() {
1. // creating the frame with the title
2. f = new Frame ("Mouse Adapter");
3. // adding Mouse Listener to the Frame
4. [Link](this);
5. // setting the size, layout and visibility of the frame
6. [Link] Size (300, 300);
7. [Link] Layout (null);
8. [Link] (true);
9. }
0. // overriding the mouseClicked() method of the MouseAdapter class
1. public void mouse Clicked (Mouse Event e) {
2. // creating the Graphics object and fetching them from the Frame object using getGraphics()
method
3. Graphics g = [Link]();
UNIT -II
4. // setting the color of graphics object
5. [Link] Color (Color. BLUE);
6. // setting the shape of graphics object
7. [Link] ([Link](), [Link](), 30, 30);
8. }
9. // main method
0. public static void main(String[] args) {
1. new Mouse Adapter Example();
2. }
3. }

Output:

Adapter Class is a simple java class that implements an interface with only an empty
implementation. Let’s suppose, there is an interface Intref which has various methods as
follows:
Interface Intref {
UNIT -II
Public void m1 ();

Public void m2 ();

Public void m3 ();

Public void m1000 ();

As, in this interface, there are 1000 methods present and if we want to implement this
interface in any particular class then we will have to override all of these 1000 methods of
Intref in the implementation class. We can do this as follows:
Class Test implements Intref {

Public void m1 () {

// some statements

Public void m2 () {

// some statements

Public void m3 () {

// some statements

:
UNIT -II
:

Public void m1000 (){

// some statements

The problem with this approach is that it increases the length of the code and reduces
readability. We can solve this problem by using the Adapter class. Instead of
implementing the interface if we extends the Adapter class to our Test class then we will
have to provide the implementation only for the required methods that we will needed at
the time of implementation and we are not responsible to provide the implementation for
each and every method of the interface, so that the length of the code will be reduced. So,
firstly we have to create a class Adapter and we have to implement the intref interface
and only provide the empty implementation for each and every method of the Intref
interface.
And we will have to use an abstract modifier while creating an Adapter class because we
are providing an empty implementation to the methods of an interface and we know that
if the implementation of the method is incomplete then we are restricted to create an
object of that class. Thus for restricting the creation of an object of the Adapter class we
should have to use an abstract modifier with the Adapter class.
Abstract class Adapter implements Intref {

Public void m1 (){};

Public void m2 () {};

Public void m3 () {};

:
UNIT -II
:

Public void m1000 () {};

Now we have to extends this Adapter class in our Test class and just override those
required methods which we will require in the Test class.

Class Test extends Adapter {

Public void m1 () {

[Link] ("This is m1 () method.");

Public void m80 {

[Link] ("This is m80 () method.");

Example 1:

/*package whatever //do not write package name here */

[Link].*;

interface Intref{
UNIT -II

publicvoidm1();

publicvoidm2();

publicvoidm3();

publicvoidm4();

publicvoidm5();

publicvoidm6();

publicvoidm7();

publicvoidm8();

publicvoidm9();

publicvoidm10();

Abstract class Adapter implements Intref{

// providing the empty implementation

publicvoidm1(){};
UNIT -II

publicvoidm2(){};

publicvoidm3(){};

publicvoidm4(){};

publicvoidm5(){};

publicvoidm6(){};

publicvoidm7(){};

publicvoidm8(){};

publicvoidm9(){};

publicvoidm10(){};

classGFG extendsAdapter{

@Override

publicvoidm1(){

[Link] ("This is m1 () method.");


UNIT -II

@Override

publicvoidm7(){

[Link] ("This is m7 () method.");

Public static void main (String[] args) {

GFG g = new GFG();

g.m1();

g.m7();

}}

Output
This is m1 () method.

This is m7 () method.
UNIT -II

r
e
a
d

a
b
o
u
t

t
o
UNIT -II
UNIT -II
UNIT -II

You might also like