Java Notes
Java Notes
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.
Buzzwords of Java
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
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.
1. Primitive Types: byte, short, int, long, float, double ,char, Boolean
2. Non primitive Data Types: class, object, string, interface, string, Array.
• 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.
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.
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
+ Addition 5+3=8
- Subtraction 5-3=2
* Multiplication 5 * 3 = 15
/ Division 6/3=2
% Modulus (remainder) 5 % 3 = 2
2. Unary Operators
3. Relational Operators
== Equal to a == b
!= Not equal to a != b
4. Logical Operators
` `
5. Bitwise Operators
` ` Bitwise OR
~ Bitwise NOT ~5 = -6
6. Assignment Operators
= 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
Example:
8. Other Operators
Operator Description
?: Ternary conditional
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(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(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
switch statement
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.
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(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
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.
package com.java4coding;
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;
Output:
The number is 1
The number is 2
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
package com.java4coding;
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;
}
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;
if ([Link] == 3) {
return "Advith";
}
return "Manu";
}
Output:
Advith
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 Box {
double width;
double height;
double depth;
UNIT -II
}
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 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.
Access_specifier ClassName ()
{
//Constructor body
}
Syntax to create object: ClassName classVar = new ClassName();
Example
package com.java4coding;
public ConstructorDemo ( ) {
[Link]("Default Constructor");
}
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
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:
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.
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
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
java
CopyEdit
StringBuilder sb = new StringBuilder("Hello");
[Link](" World!");
Common Methods:
o append(), insert(), delete(), reverse(), toString()
UNIT -II
3. StringBuffer Class
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.
class Outer {
private String msg = "Hello";
class Inner {
void showMessage() {
[Link](msg); // Accessing outer class member
}
}
}
class Outer {
static String msg = "Hello";
class Outer {
void display() {
String localVar = "Local";
class LocalInner {
void print() {
[Link](localVar);
}
}
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.
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:
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:
Modularity:
Promotes a clear separation of concerns, making code easier to understand, maintain, and debug.
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:
this keyword is used to resolve the conflicts between instance variables and local variables.
package com.java4coding;
public Demo ( ) {
}
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;
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
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
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";
}
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).
class Math {
int add(int a, int b) {
return a + b;
}
class Animal {
UNIT -II
void sound() {
[Link]("Animal makes sound");
}
}
Benefits of polymorphism:
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.
dim2 = b;
double area() {
super(a, b);
super(a, b);
}
UNIT -II
class FindAreas {
In this chapter you learn the differences between java abstract class and 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
UNIT II
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.
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.
try {
...
} catch (Exception_class_Name reference) {
}
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
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.
finally block can be used to put "cleanup" code such as closing a file, closing connection , to release resources
etc…
Output:
5
finally block is always executed
rest of the code...
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).
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.
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.
class Excep13 {
void validate(int age) throws IOException {
if (age < 18)
throw new IOException("not valid");
else
[Link]("welcome to vote");
}
}
}
}
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])
void method1() {
try {
method2();
} catch (IOException exp) {
[Link]("exception handled");
}
Output:
exception handled
normal flow...
Throw Throws
You can throw only one You can declare multiple exceptions.
exception.
UNIT -II
If you are creating your own Exception then that is known as custom exception or user-defined exception
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.
n Java, files and I/O streams are part of the [Link] and [Link] packages, which allow you to read from and
Example:
Import [Link];
If ([Link] ()) {
[Link] ("File exists");
} else {
[Link] ("File does not exist");
}
Use Input Stream and Output Stream for reading/writing binary data.
Example:
Import [Link];
Import [Link];
Import [Link];
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]();
[Link]();
}
}
UNIT -II
File Reader and File Writer are character-based equivalents of byte streams.
Example:
Int c;
While ((c = reader. read ()) != -1) {
[Link](c);
}
Import [Link];
Import [Link];
String line;
While ((line = [Link]()) != null) {
[Link] (line);
}
[Link] ();
}
UNIT -II
}
[Link]-With-Resources (Auto-Close)
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.
2. Character Streams
3. Buffered Streams
4. Data Streams
DataInputStream / DataOutputStream
5. Object Streams
ObjectInputStream / ObjectOutputStream
6. Standard Streams
[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
UNIT III
PACKAGE:
✓ There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
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:
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;
[Link] ("Hello") ;}
}
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
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
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
packagep1;
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;
{
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;
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;
Protection2() {
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
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
Entire operations of Array List are same for Linked List, but
Vector
Java Queue
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
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
Java Map
1. Tree Map.
2. Hash Map.
UNIT -II
3. Linked Hash Map.
4. Hash table.
5. Properties
Tree Map
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
UNIT IV
MULTITHREADING
Multi tasking is the ability of an operating system to run multiple tasks concurrently. There are two
main types.
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.
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
CREATING 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
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
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);
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 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
SQL
SQL stands for Structured Query Language in DBMS and is used to communicate with database.
SQL is a standard proposed by ANSI.
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:
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.
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
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).
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
[Link]("[Link]");
For newer JDBC versions, loading the driver explicitly might not be required.
3. Establish a Connection
4. Create a Statement
Use Statement, Prepared Statement, or Callable Statement depending on your use case.
You can use execute Query() for SELECT and execute Update() for INSERT,
UPDATE, DELETE.
while ([Link]()) {
[Link]([Link]("column_name"));
}
[Link]();
[Link]();
[Link]();
UNIT -II
Class Description
UNIT V
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.
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.
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: 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:
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.
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 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.
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.
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:
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.
AWT does not inherently support advanced UI features such as drag-and-drop, rich text
editing, or complex component arrangements without significant custom coding.
While AWT provides layout managers, achieving complex and flexible component
arrangements can be challenging and require intricate configurations.
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.
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
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.
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
// main function
[Link](button);
UNIT -II
[Link](500, 500);
[Link](null);
[Link](true);
}}
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.
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.
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.
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()
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()
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.
[Link].*;
GFG Top()
UNIT -II
// Component Creation
[Link](this);
// add Components
add(text Field);
add(button);
UNIT -II
// set visibility
Set Visible(true);
}
UNIT -II
Output
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.
[Link].*;
GFG2()
// Component Creation
[Link](other);
UNIT -II
// add Components
add(text Field);
add(button);
// set visibility
set Visible(true);
newGFG2();
Import [Link].*;
UNIT -II
GFG2 gfgObj;
Other(GFG1 gfgObj) {
[Link] = gfgObj;
}}
UNIT -II
Output
[Link].*;
[Link].*;
GFG3()
// Component Creation
UNIT -II
[Link](newActionListener() {
Text [Link]("Anonymous");
});
UNIT -II
// add Components
add(text Field);
add(button);
Set Size(300,300);
// set visibility
Set Visible(true);
newGFG3();
}
UNIT -II
Output
Handling anonymously
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){}
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.
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.
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:
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.
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.
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 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
o It is Flexible, can enable different types of application models for event flow and
propagation.
o It provides support for the backward binary compatibility with the previous model.
The below is a Java program to handle events implementing the event deligation model:
UNIT -II
[Link]:
Import [Link].*;
Import [Link].*;
Output:
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.
The signature of 5 methods found in Mouse Listener interface are given below:
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:
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.
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
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.
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
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.
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]
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]
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 ();
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
:
// 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 {
:
UNIT -II
:
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.
Public void m1 () {
Example 1:
[Link].*;
interface Intref{
UNIT -II
publicvoidm1();
publicvoidm2();
publicvoidm3();
publicvoidm4();
publicvoidm5();
publicvoidm6();
publicvoidm7();
publicvoidm8();
publicvoidm9();
publicvoidm10();
publicvoidm1(){};
UNIT -II
publicvoidm2(){};
publicvoidm3(){};
publicvoidm4(){};
publicvoidm5(){};
publicvoidm6(){};
publicvoidm7(){};
publicvoidm8(){};
publicvoidm9(){};
publicvoidm10(){};
classGFG extendsAdapter{
@Override
publicvoidm1(){
@Override
publicvoidm7(){
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