CONTENTS
Java is a
by Sun Mi
designed t
UNIT - I device that
and operat
1.1 Introduction of Java l toe
1.2 What is JVM 4 1, Pla
1.3. Inheritance j “Write On
" generates
1.4 Exception Handling in Java 2. Ob
1.5. Multithreading in Java ulanguage,
1.6 Java Applet 1 ar
1.7 Socket Overview 20program™
aspects lil
1.8 Java Database Connectivity 24 ar Au
1.9 What is API? 27deallocati
developer:
UNIT - I a
include
2.1 Java ResultSetMetaData Interface 8Bnetworkin
2.2 Setter and Getter Methods in Java 396. Se
2.3 Creation of javabean wee on
. Mu
2.4 Servlet Architecture Al applicatio
2.5 Servlet Interface 4g 2nd tespo
2.6. http get request java 45 mechan
2.7 Session Tracking in Servlets, 4g applicatic
programs
UNIT - II 2 &
which cor
3.1 Introduction to JSP nave
‘
UNIT - Iv oe
4.1 What Is Client-Server Architecture 31
4.2 RMI (Remote Method Invocation) a
4.3 Parameter Passing , dave
44° What is HB oo
66ADVANCED JAVA PROGRAMMING
1.1 INTRODUCTION OF JAVA.
Javan wa widely wed, high-level, object oriented programming language developed
yee Aeragyatenne quan owned by Oracle Corporation) inthe wid-1990s. 1. ve
ae aa to be: platform independent, meaning hat Java programs ean run om any
aoe ial bossy Java Virtual Machine LIVM), regardless of the underlying hardware
sul operating system.
Key Features of Java
4 1. Platform Indepe 1: Java achieves platform independence through it
Write Onee, Ren Anywhere” (WORA) principle, Once a Java prog
aeenne celsteeade, which ean be exceted on any device with a JVM.
13 2 Opject Oriented: Java is primarily an object-oriented programming (OOP)
‘sit follows the prineiples of encapsulation, inheritance,
nd abstraction.
14. language
polymorphism
eee Senta’ ava syntax is largely influenced by C and C++, making it familiar to
9 programmers wth background i these languages, However, Java simplifies certain
Pevects lke memory management by introducing automatie garbage callection
t. Automatic Memory Management: Java manages memory allocation and
27 |deallocation automatically through its garbage collection mechanism, relieving
developers from man Jory management tasks.
Rich Standard Li Java provides a vast ry (Java API) that
includes elasser and methods for a wide range of tasks, from basic VO to advanced
networking and GUI development.
Security: Java has built-in security features, such as bytecode verification,
which ensures that Java programs do not violate security constraints during runtime.
&
7, Multithreading: Java supports multithreading, allowing developers to create
41. applications that can execute multiple threads concurrently, improving performance
and responsiveness.
8. Robustness and Portability strong type system, exception handling
45. mechanism, and striet compile-time checking contribute to the robustness of Java
4a applications. Additionally, its portability across different platforms ensures that Java
programs behave consistently across diverse environments. _
‘9. Community Support: Java has a vast and active community of developers,
which contributes to its ecosystem with libraries, frameworks, and tools,
Java Editions
ot » Java Standard Edition (Java SE): It is the core Java platform used for
‘eveloping desktop, web, and server applications.
« Java Enterprise Edition (Java BE): [tis set of specifieations for developing
‘enterprise-level applications, particularly web applications that run on servers
57 + Java Micro Edition (Java ME): It is a platform for developing applications
60 or mobile devices, embedded systems, and other small-footprint devices.
ry Java Development Tools
+ Java Development Kit (JDK): It includes tools for developing, debugging,
66 ‘ind monitoring Java applications, It contains the Java compiler, runtime
nvironment, and other development tools.
* Integrate lopment Environments (IDEs): Popular Java IDEs
include Eclipse, Intellid IDEA, and NetBeans, which provide features like code
completion, debugging, and project management.Sixth Semester, Advanced J
2-2028
Java's versatility, portability, and extensi
developing a wide range
web services
\ “Hello, World!” is a simple program that outputs Hello, World! on the screen
le program, it’s often used to introduce a new programming
Since it's a very simple program, it's
language to a newbie
Lot's explore how Java “Hello, World!” program works
Java “Hello, World!” Program
Your First Program
classHelloWorld{
public static void main(String[] args)(
System.out.printin(‘Hello, World!”):
Output
Hello, World!
How Java “Hello, World!” Program Works?
Basic features:
Basic features of Java are
ieee 9
of
Java
Simple
J
According to Sun Microsyst
because
* Java syntax is based on C++ (so easier for programme!
* Java has removed many complicated
explicit pointers, operator overloading, etc
‘There is no need to re
nove unreferenced objec
Garbage Collection in Java
of applications, from enterprise
java is very easy to learn, and its syntax is simple, clean and e.
a Programming
ecosystem make it a popular choice
software to mobile apps ang
oe
—
°
sabe Tine
and rarely-used features, for example,
's because there is an Automati¢
to understand,
Java hinguage is a simple programming language
's to learn it after C++),
ol
Ja
Object
jects
ol
lo
B
JavaLP. University-IB:Tech} Akash Book 2023-3
2 Object
DPS and sa
nted
Java is an object-oriented programming language. Everything in Java isan oles
screen, § OS rena mane we argnize ot oftware ax i combination of different type of
objects that incorporate both data and behavior
amming arate oh eee Z
Object-oriented programming (OOPs) is & methodology that simplifies sofware 1
development and maintenance by providing some rules
Basie concepts of OOPS are:
1. Object
2.01
3, Inheritance
4. Polymorphism
5, Abstraction
6, Encapsulation
Platform Independent
Java is platform independent because it is different from other language like €
Cas, ote which are compiled into platform specific machines while Java is write once
vn anywhere language. A platform is the hardware or software environment in which
a program runs
‘There are two types of platforms software-based and hardw are-hased. Java provides
a software-based platform.
‘The Java platform differs’ from most other platforms in the sense that it is a
‘software-based platform that runs on top of other hardware-based platforms. It has two
components:
(a) Runtime Environment
(b) API(Application Programming Interface)
Secured
Java is best known for its security. With Java, we ean develop virus-free systems
Java is secured because:
* No explicit pointer
« Java Programs run inside a virtual machine sandbox
understand.
ng language
t after C++).
ne ¢ the Java Runtime Environment
the Java Virtual Machine
Jkage for the classes of the
* Classloader: Classloader in Java is @ part of
. (JRE) which is used to load Java classes into
n Automatic dynamically. It adds security by separating the pacva Programming
41-2023 sixth Semester, Advanced J
7 that are imported from network sources
ea ae ments for illegal code that can violate
« Bytecode Verifier: It checks the code fra
access rights to objects.
Ti determines what resources a class can access such as
* Security Manager sw
reading and writing to the local dis!
sen : fault. Some security can also be
‘L, JAAS, Cryptography, ete.
es these sect jes by def
Java language provides these securiti It
tion developer explicitly through SS
provided by an applic
Robust
The English mining of Robust is
strong. Java is robust because:
strong memory management
# There is a lack of pointers that avoids security problems,
«+ Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
* Tras
anymore.
« There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent
features, for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory
for both 32 and 64-bit architectures in Java.
Portable: Java is portable because it facilitates you to carry the Java bytecode to
any platform. It doesn’t require any implementation.
High-performance: Javais faster than other traditional interpreted programming
languages because Java bytecode is “close” to native code. It is still a little bit slower
than 2 compiled language (e.g., C++). Java is an interpreted language that is why it is
slower than compiled languages, e.g., C, C++, ete. 7
Distributed: Java is distributed because it facilitates users to create distributed
applications in Java, RMI and EJB are used for creating distributed applications. This
cature of Java makes us able to access files by calling the methods from any machine
on the internet
Multi-threaded: A thread is like a separate program, executing concurrently.
We can write Java programs that deal with many tasks at once by defining multiple
threads. The main advantage of multi-threading is that it doesn't occupy memory for
‘ach thread. It shares a common memory area. Threads are important for multi-media
Web applications, ete 2
Dynamic: Java is a dynamic language. It suppoi
It means class
language
s the dynamic loading of classes.
+s are Joaded on demand. It also supports functions from its native
Le, Cand C++
1.2 WHAT IS JVM.
TheJava Virtual Machine (JVM) isacrucialcomponentof the Java Runtime Environment
(JRE) and the Java Development Kit (JDK). It plays a central role in the
Java bytecode, enabling Java programs to run on any d
installed, regardless of the underlying hardware
execution of
evice or platform that has a JVM
rating system. It is:
or opt
1. A spe
implementatic
has been prov
2. An im
Environment)
3. Runti
to run the jav
Functions o
1, Bytee«
platform-inde
for interpretit
2,Memo
including the
by allocating
use, and man
3. Platf;
operating sys
enables Java
device or plat
4. Secur
programs rur
causing harm
access to syst
5. Just-
include a JIT
at runtime fo
native speed,
6. Class
classes into 1
class variabl
7. Exect
and profiling
bottlenecks,
Componen
1. Class
program.
2, Runt
the method <
3. Exec
performs JT1
4. Nati
native code \
Overall,
underlying I
of Java pro;
performancean violate
such as
an also be
raphy, ete.
java Virtual
. application
in Java. All
dependent
.rchitecture
of memory
bytecode to
ogramming
» bit slower
is why it is
distributed
ations. This
ny machine
currently.
ng multiple
memory for
nulti-media,
1g of classes,
n its native
nvironment
xecution of
hasaJVM
|
LP. University-IB.Tech]-Akash Books 2023-5
1. A specification where working of Java Virtual Mach
implementation provider is independent to choo:
has been provided by Oracle and other companies,
2, An implementation Its implementation is known as JRE (Java Runtime
Environment).
is specified. But
the algorithm, Its implementation
Runtime Instance Whenever you write java command on the command prompt
to run the java class, an instance of JVM is created.
Functions of the JVM
1. Bytecode Execution: Wher. a Java program is compiled, itis translated into
platform-independent bytecode instead of native machine code. The JVM is responsible
for interpreting this bytecode and executing it on the target platform.
2, Memory Management: The JVM manages memory allocation and deallocation,
including the automatic garbage collection process. It ensures efficient memory usage
by allocating memory for objects, reclaiming memory from objects that are no longer in
use, and managing memory fragmentation
3. Platform Independence: The JVM abstracts the underlying hardware and
operating system, providing a uniform execution environment for Java programs. This
enables Java applications to be truly platform-independent, as they can run on any
device or platform with a compatible JVM.
4, Security: The JVM enforces various security measures to ensure that Java
programs run safely. It implements bytecode verification to prevent malicious code from
causing harm to the system. Additionally, it provides a security manager that controls
access to system resources based on a set of predefined permissions.
5. Just-In-Time (JIT) Compilation: Many modern JVM implementations
include a JIT compiler, which dynamically compiles bytecode into native machine code
at runtime for improved performance. This allows frequently executed code to run at
native speed, enhancing the overall performance of Java applications.
6. Class Loading and Initialization: The JVM is responsible for loading Java
classes into memory as they are needed during program execution. It also initializes
class variables and static blocks before the first use of a class.
7. Execution Monitoring and Profiling: The JVM provides tools for monitoring
and profiling Java applications, allowing developers to analyze performance, identi
bottlenecks, aind optimize code for better efficiency.
Components of the JVM
1. Class Loader: Loads Java class files into memory aé they are referenced by the
program.
2, Runtime Data Area: Memory area divided into several components, including
the method area, heap, stack, and program counter.
3. Execution Engine: Interprets and executes bytecode, and in some cases,
performs JIT compilation.
4, Native Interface: Provides a mechanism for Java programs to interact with
native code written in languages like C and C++.
Overall, the JVM serves as a critical intermediary between Java bytecode and the
underlying hardware and operating system, enabling platform-independent execution
of Java programs while providing features like memory management, security, and
performance optimization,‘The JVM performs following operation:
* Loads code
* Verifies code
* Executes code
+ Provides runtime environment
JVM Architecture
‘The internal architecture of JVM contains classloader, memory area, execution
engine ete.
() Classloader: Classloader is a subsystem of JVM which is used to load class
files. Whenever we run the java program, it is loaded first by the classloader. There are
three built-in classloaders in Java
(a) Bootstrap ClassLoader: TI
s is the first classloader which is the super class
of Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package clas: ava.net package classe
package classes, java.io package classes, java.sql package classes ete.
(b) Extension ClassLoader: This is the child classloader of Boot:
classloader of System classloader. It loades the jar files located inside
jrefliblext directory.
(c) System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to current
directory. You can change the classpath using “-cp” or “-classpath” switch. It is also
known as Application classloader.
1. Let's see an example to print the classloader name
2. public class ClassLoaderExample
{
s, java.util
rap and parent
|AVA_HOME/
public static void main(String[] args)
{
// Let's print the classloader name of current class.
WApplication/System classloader will load this class
Class c=ClassLoaderExample.class;
System.out.println(c.getClassLoader());
/Mf we print the classloader name of String, it will print null because it is an
11. /in-built class which is found in rt jar, so it is loaded by Bootstrap classloader
12, System.out.printIn(String.class.getClassLoader());
13.)
14.)
Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null
These are the internal classloaders provided by Java. If you want to create your
own classloader, you need to extend the ClassLoader cla:
OHI AA HE
Ss
(2) Class(Method) Area: Class(Method) Area stores per-class structures such as
the runtime constant pool, field and method data, the code for methods,
(3) I
as
and play
Fa
An
its meth
6)
address
)!
@)
(a)
(b)
(c)
(a)
CLASS
Classes
variablstil
nt
1E/
ion
nt
Iso
ler
ur
LP. University 1B-Tech] Akash Books 2023-7
(3) Heap: I is the runtime data area in which objects are allocated.
(4) Stack: Java Slack stores frames. It holds local variables and partial results,
and plays a part in method invocation and r
ach thread has a private JVM stack, created at the same time as thread
ated each time a method is invoked. A frame is destroyed when
A new frame is er
jon completes.
its method invor
(5) Progra
address of the J
(6)Native
(7) Execution Engine: It cont:
m Counter Register: PC (program counter) register contains the
‘tion currently being executed.
Method Stack: It contains all the native methods used in the application.
(a) A virtual processor
(b) Interpreter
(c) Just-In-Time(JIT) compiler
(d) Java Native Interface
CLASS & OBJECT
Classes are the building blocks of a java application. A class can contain methods,
variables, initialization code and even other classes. We can declare a class with class
keyword
class classname
(
datatype variablename;
return type methodname(argument list)
t
statement block;
i
)
‘Two types of variables can be defined in a class ~ instance variables and static
variable, Every object has its own set of instance variables. If we don't initialize an
instance variable during declaration, then it takes a default value appropriate for its
type.
‘As with variables, methods defined in a class may be instance methods or static
methods.
‘An instance method is associated with an instance of the class, but each instance
does not really have its own copy of the method
(1) Static members: Members that are declared with the static modifier live in the
class and are shared by all instances of the class. Any modification on static variable in
one instance, will affect other instances of the same class. Since static members exist in
the clase itself, independent of any instance, we can also access them directly through
the class.
(2) Method: Method appears inside class bodies. They contain local variable
declaration and statement. A method in a java always specifies a return type. There is
no default return type.
Static method belongs to the class and not to an individual instance of the class. It
can be invoked by name, through the class name, without any objects around. A static‘Advanced Java Programming
Sixth Semester,
lass. It ean not directly see
82023
ly access only other static members of the el
any instance methods.
Java is a two-step process. F
ble does not define an object instead,
Second, we must acquire an actual,
‘able. We can do this using the new
method can direct
any instance variable or call
(3) Object: Creating an object of a class in
must declare a variable of the class type. This varial
it is simply a variable that can refer to an objer
physical copy of the object and assign it to that vari
operator
erthe new operator dynamically allocates memory fo
iss. First we
yr an object and returns a
reference to it
Classnameobjectname = new classname) ;
classname.variablenaine
(4) Array: An array is a group of similar type of data that are referred
common name.
Array of any type can be created and may have one or more dimensions. A specific
clement in an array is accessed by its index. In Java, array index start from zero.
The declaration statement of an array can not allocate any memory space to the
array, We must allocate space to array by using new operator.
(i) One-dimensional array: The general form of one-dimensional array is
(i) Multidimensional array: In Java, multidimensional arrays are actually arrays
of arrays. ‘’he general form is
(5) String: A string is a sequence of characters. Java implements strings as objects
of type String.
to by a
After creating a String object, we can not change its contents. If it is necessary to
modify, then we have to create a new string object.
(6) Vector: The Jave.util package has a class called vector. It permits an array
to store different elements that are of different class. We need to include the import
statement import java.util." to use the vector class.
It is also an expandable array of objects. The array grows larger as more elements
are added to it. The array may also be reduced in size after some of its elements have
been deleted.
We can not directly store simple(primitive) data type in a vector. We can only store
objects,
‘Vector automatically increases its size when needed.
1.3 INHERITANCE
Inheritance is a fundamental conce|
(methods and fields) from another el:
er class (superclass or parent class). Thi
code reuse, modularity, and hierarchical organization of classes, a
Syntax of Inheritance in Java
In Java, inheritance is achieved
y using the a
that inherits from a superclass. The syntax is a follow ent? Create & Subclass
yyntax is as follows:
JavaCopy code
class Superclass
Example:
javaCopy code
class Superelass extends Superclass
Ani
h
‘Type
inter!
inher
of int
A
execuec
we
ad,
ial,
ew
ecific
» the
rays
ects
ray
port
ents
rave
ding
viors
jotes
class
LP. University-1B-Tech|-Akash Books 2023-9
class Animal void make
‘ound —_ “Some generic sound..."); }] class Dog exter
Animal"Canine” void make Sound “Woof!” ee
In this example:
+ Animal is the superclass with a field species and a method makeSound(),
+ Dog is the subclass that extends Animal, It inherits the specie:
overrides the makeSound0 method with its own implementation nn “4
Types of Inheritance in Java
1. Single Inheritance: A subclass inherits from only one superclass.
2, Multilevel Inheritance: A subclass becomes a superclass for another subelass,
¢ a chain of inheritance.
creati
3, Hierarchical Inheritance: Multiple subclasses inherit from a single superclass
4, Multiple Inheritance (through interfaces): A class implements multiple
interfaces, effectively inheriting from all of them. Java does not support multiple
inheritance of classes to avoid the diamond problem, but it supports multiple inheritance
of interfaces.
Access Modifiers and Inheritance:
+ Public: Subclasses can inherit and access public members of the superclass.
* Protected: Subclasses can inherit and access protected members of the
superclass, but only within the same package or through inheritance.
* Default (no modifier): Subclasses can inherit and access default members of
the superclass only if they are in the same package.
+ Private: Subclasses cannot directly inherit or access private members of the
superclass.
Method Overriding:
‘Subclasses can override methods inherited from the superclass by providing a new
implementation. This allows subclasses to customize behavior while still benefiting
from code reuse.
Super Keyword:
‘The super keyword in Java is used to refer to members of the superclass within
the subclass. It can be used to call superclass constructors, access superclass methods
or fields, and differentiate between overridden methods and superclass methods with
the same name.
In summary, inheritance in Java allows classes to inherit properties and behaviors
from other classes, promoting code reuse and facilitating hierarchical organization of
classes. It is a key concept in object-oriented programming and is widely used in Java
programming.
‘Threads in java have five characteristics.
1. Thread body: This is the sequence of instructions for the thread to perform.
We create a thread by instantiating an object of type Thread. Java defines two ways in
which this ean be accomplished:
(i) We can implement the Runnable interface: Runnable abstracts a unit of
executable code. To implement Runnable, a class need only implement a single method
called runt }.
abstract class classname
{10-2023 Sixth Semester,
abstract returntypemethod!)
i
)
Class classname
i
final returntypemethod! )
i
statement;
’
1
final class classname
{ tha
returntypemethod( ) i
{
statement;
1
ay created Runnable Blocked thr:
Dead Will
Start()
Stop) grou
Run()
ends
Stop()
Run)
ends
V/O blocking
Resume( )
Notify()
Sleep time out vo
VO finished
Stop()
Run() cee
ends oon
will eae ), we will define the code that constitutes the new thread. This ora
run( ) returns. oon
ii) We can extend the Thread class, itself.: We can extend the Thread css!
create a new thread. Then cr i ji
crea anew thr reate a instance (object) of that class. The extending OH and
run( i
coene ‘un( ) method. We must also call start( ) to begin execution of tt
2. Thread States:
| be in one of the four st:
The:
E
very thread, after creation and before destruction, will"
ates —
's newly created, runnable, blocked and dead. hasash bOOKS 2023-11
(i) Newly ¢
ted: A thread enters the newly created b
is in the new state or born state immediately after creation,
(ii) Runnable: Once we invoke the
(iii) Blocked: The blocked state is ¢
when call the suspend( ) method
by using a new operator. It
rt( ) method, the thread is runnable.
tered when one of the following events occurs -
(b) call for wait( ) method
(c) waiting for VO operation
(d) the thread will join( ) another thread
(iv) Dead: A thread is dead for any one of the two reasons:
(a) it dies a natural death b
b) it dies abruptly because an uncaught exception terminates the run method.
3. Thread priority: Every thread in java is assigned a priority value. When more
than onethread is competing for CPU time, the thread with highest priority value is
given preference. Wecan also use the Thread class constants as follows
Thread. MIN_PRIORITY = 1
‘Thread. MAX_PRIORITY = 10
Thread.NORM_PRIORITY = 5
4. Daemon Thread: This denotes that a thread is a “server” thread. A server
thread is a thread that services client request. They normally enter an endless loop
waiting for clients requesting services.
5. Thread Group: Java allows us to group similar threads and manage them as a
group. Every thread instance is a member of exactly one thread group.
Methods of Thread class: The Thread class defines several methods as follows:
1. getName -> Obtain a thread’s name
2. getPriority -> Obtain a thread’s priority
3. isAlive -> Determine if a thread is still running
4. join -> wait for a thread to terminate
5. run -> Entry point for the thread
6. sleep -> Suspend a thread for a period of time
7. start -> Start f thread by calling its run method.
VO IN JAVA
UO Basie:
Streams: java programs perform I/O through streams. A stream is a flow of data
or a channel of communication. A stream is an abstraction that either produces or
consumes information. A stream is linked to a physical device by the java I/O system.
An input stream can abstract many different kinds of input from a disk file, a keyboard,
or a network socket. An output stream may refer to the console, a disk file or a network
connection. Java implements streams within class hierarchies defined in the java.io
package.
Byte Streams and Character Streams: - Java defines two types of streams ~ byte
and character.
Byte streams provide a convenient means for handling input and output of bytes.
‘These are used for reading or writing binary data.
Character streams provide a convenient means for handling input and output of
characters
cause the run method exits normallygr
Java Programming
fi y using two cla
are defined by using ay
TnputStream and OutputStrean
face different devices liky
thods are read( ) anq
2-2028 sixth Semester, Advanced
(i) The Byte Stream Classes: By!
hiorarchies. At the top are two abstract CU
Each of these abstract classes has several su
disk files, network connection ete. two of the
Write( ) for reading and writing bytes of data.
(ii) The Character Stream Class
class hierarchies.
: d
‘Mt the top are two abstract classes, Reader an ;
Unicode character streams, These classes define several key methods 0%
read( )and write( ) to read and write characters of data. .
The Predefined Streams: Al] java programs ees
i is system cl
package. This package defines a class called System. sys
predefined stream variables —in, out and err. These fields are declared as public,
and final within system. 7 1"
System.out refers to the standard output stream. By default, this is the console
System.in refers to standard input, which is the keyboard by default. System-err
refers to the standard error stream, which also is the console by default.
‘System in is an object of type InputStream, System.out and System.err are objects
of type PrintStream. .
Reading Console Input: In java, console input is accomplished by reading from
To obtain a character-based stream that is attached to the console, wrap
System.in ina
BufferedReader object. This object supports a buffered input stream. Its most
commonly used constructor is
BufferedReader(Reader inputReader)
Here Reader is an abstract class. One ofits subclasses is InputStreamReader whick
converts bytes to characters. To obtain an InputStreamReader object, we have to us
the following constructor
InputStreamReader(InputStreaminputStream)
The main statement is
BufferedReaderbr = new BufferedReader (new InputStreamReader( System. in);
Reading characters: - Characters from keyboard can be read as follows:
BufferedReaderbr = new BufferedReader (new InputStreamReader( System.in))
Char ¢ = (char) br.read();
Each time the read( ) is called, it reads a chara
aS it as an integer value, We are using
sading String: To read a stri :
readLine( ) which is the member of the from the keyboard, we can use the version!
a , er of the BufferedReader class.
String readLine( ) throws IOException
The statement is :
BufferedReaderbr
ew BufferedRi .
String str; feader (new InputStreamReader( System.
Str = br.readLinet );
Reading and Writi
riting Fil :
all 8 Files: Java provi
ow to ead and witt files. Inova oh ee ides a number of classes and methods
are byte-oriented,
belasses to handle
most important met
aracter streams are defined by using two
Writer. These classes handle
yut of which are
import the java.lang
Jass contains three
static
cter from the input stream at
(char) to convert it to character type.
Pwo
FileOutput
create an «
the constr
Fileln.
FileO\
Here
an input s
output str
When
Readit
Int re:
Each |
as an intes
syntax is
Writi
Void v
This 1
declared a
Closi:
Filein
fin = n
int x =
File.
fin =n
fout..
Void «
Exception
file not fo
programs
them app:
Key
1. Ex
that are ¢
checked
*Ch
by the me
such as fil
FileNotF
* Un
do not nee
errors, suvd
wo
le
are
ree
atic
cole,
err
cts
om
ap
ost.
ich
LP. University-1B-Techl-Akash Book
FikeOutpuiStrcnm, which crate byte ssa hake gp elaputseeam and
create an object of one of these classes, specify thence dg Te open a file
the constructor. The general form is
2028-18
we simply
me of the file as an argument to
FileInputStream(String filename) throw
ileNotPoundException
FileOutputStream(String filename) throws FileNotFoundxcept
‘oundxception
Here, filename specifies the na
an input stre:
of the file that we want to open. When we creat
When an output file is op existing file by the same name is destroyed,
le:- To read from a file, we can use a version of read( )
Int read( ) throws IOException
am, if the file does not ex
ned, any pre
Reading from Fi
ng as follows:
Each time that it is called, it reads a single byte from and returns the
as.an integer value. Tho endl) returns 1 when the end af the fle lsenemeeved te
syntax is
} Writing to file: To write to a file, we can use the write( ) method as follows
Void write(int byteval)throws IOException
This method writes the byte specified by byteval to the file. Although byteval is
declared as an integer, only the low-order eight bits are written to the file, The syntax is,
Closing a file: We can close a file by using close( ) method. The syntax is
FileInputStream fin;
fin
new FileInputStream(“filename”);
int x = fin.read( );
FileOutputStreamfout;
fin = new FileQutputStream(“filename”);
fout.write(integer value };
Void close( ) throws IOException;
1.4 EXCEPTION HANDLING IN JAVA
Exception handling in Java is a mechanism used to deal with runtime errors or
exceptional conditions that occur during the execution of a program. These exceptional
conditions, also known as exceptions, can include situations such as divide by zero,
file not found, null pointer dereference, etc. Proper exception handling ensures that
programs can gracefully recover from such errors and continue execution or handle
them appropriately.
Key Concepts in Exception Handling:
1. Exception Classes: Exceptions in Java are represented as objects of classes
that are derived from the Throwable class. ‘There are two main types of exception:
checked exceptions and unchecked exceptions.
* Checked Exceptions: These are exceptions that must be eaught or declared
by the method in which they may occur. They are usually related to external factors
such as file /O errors or network connectivity issues. Examples include 1OException,
FileNotFoundException, etc.
* Unchecked Exceptions: Also known as runtime exceptions, these exceptions
do not need to be explicitly caught or declared. They typically arise from programming
crrors, such as attempting to access a mull object or dividing by zero. Examples includemming
ester, Advanced Java Prog!
Sixth Sem
14 2028
ticExeeption, cte
w handling in Java is typically done using (7c
NullPointerException, Arithme
9, try-cateh Blocks: Exceptio
Docks
«eho try block contains the code that might generate 20 exception.
the exception if it occurs. Multiple cate,
block catches and handles
blocks ean be used to handle different types of exceptions
+ vs finally block (optional) is used to execute code that must be run regardless of
whether an exception is thrown or not (e.g. closing resources)
rns can also be explicitly thrown using
3. Throwing Exceptions: In Java, exceptio
as occurred under
tho throw keyword, This is typically done to indicate that an error hy
conditions.
4. Exception Propagation: If an exception is not c:
propagated up the call stack to the calling method. If the exception is not
til it reaches the top-level method (e.g., main
spe
aught within a method, it is
caught there,
at runtime.
it continues to propagate v
Advantage of Exception Handling
‘The core advantage of exception handl
application. An exception normally disrupts the normal flow of the
why we need to handle exceptions. Let's consider a scenario:
statement 1;
Jing is to maintain the normal flow of the
application; that is
statement 2;
statement 3;
statement 4;
statement 5y/exception occurs
statement 6;
statement 7;
statement 8;
9. statement 9;
10. statement 10;
sen uPeene her ae 10 statements in Java program and an exception occurs
: : 6 ext
be executed fratello handing, ee 7 will not
will be executed. Tha’ is why we use exception handling in Java. a
1.5 MULTITHREADING IN JAVA
Multithreading is a programming concept in whi
Mii pt in which the applicati :
tial ew pr We ao a
2.
3.
5.
6.
Simple example of Applet by appletviewer tool:mming
sixth Semester, Advanced JAVA Progra!
18-2028 sixth S er tool, ereate an applet that contains am
‘To execute the applet by arp ran it by: appletviewer First.java tn ‘This paran
vsmament and compile it, After a ae
Seer Hr itis for testing purpose only. a
file is not required bu
1. /iirst.jav ent
> import java.applet- Applets containing the
3 Q 2, destro
3 ava.awt Graphics:
3 import jaeaaek Graphs sents toe
‘public class First extends App! applet needs
; + The |
6. public void paint(Graphies ©) ee
+, gdrawStringt*welcome to applet”,150,150); fom
8 < APPLE
a CODEBA
wo) CODE
1. :
12,
ae ite in command prompt: ee
‘To execute the applet by appletviewer tool, write in VSPACE
c:\>javae Firstjava :
c\>appletviewer Firstjava a
thod for apple:
+ The Applet Class: The applet class defines all necessary met
cxecution, such as starting and stopping. It also provides methods that loa
PAMAM NAME = AttributeNam
JAVPLET>
+ CODEBASE: It ix an optional attribute
applet code, which is the directory that, wil
clans file specified by the CODEtag.
that gives the
that, specifies the base URL of the
II be searched for the applet's
executabl
+ CODE: It is a required attribute
applets’scompiled .class file
© ALY: This tag is an optional
that should be displayed if t
currently run java applets.
name of the file containing our
attribute used to specify a short text message
ecognizes the APLET tag but can not
Name ix an optional attribute used to specify a name for the applet
+ NAME:
| © WIDTH and HEIGHT: WIDTH and HEIGIT are required attributes that give
| the wize of the applet display ares
ignment of the applet
pecifies the
«ALIGN: It in an optional attribute that 9?
« VAPACE and HSPACE: These attributes are option
apace above and below the applet HSPACE specifies the space on
|. VSPACE specifies the
ach side of
the apple.
yecify applot-specific
+ PARAM NAME and VALU
HTML page
«PARAM tay, ase LO SP
arguments in anng
ter, Advanced Java Programming
KET OVERVIEW
een.
Sixth Sem
1.7 soc
de the communication
1 is one endpoint of
rent computers o
TCP layer can identi
20-2028
two computer i
n link between ¢,
‘A socket is boung,
data is destined,
mechanism betw ty,
ee tworway communicaio!
ron the same computer.
ify the application that
Sockets provi
Internet. J
programs running on di
a port number so that the
TYPES OF SOCKETS:
1, Stream Sockets (TCP):
* TCP (Transmission Control
connection between two hosts over a network.
are implemented using TCP.
bidirectional, byte-stream communicat
guaranteed to arrive in the order it was sex
Protocol) provides a reliable, stream-orieny
* Stream sockets
+ They provide a reliable, tion channel
* Data sent through a stream socket is
and without duplication.
2, Datagram Sockets (UDP):
+ UDP (User Datagram Protocol) provides
service,
+ Datagram sockets are implemented using UDP.
o munication channel.
a connectionless, unreliable datagrat
+ They provide an unreliable, connectionless com
* Data sent through a datagram socket may arrive out of order, be duplicated,
not arrive at all.
Socket Operations:
1. Socket Creation: A socket is created using the socket() system call, whit
returns a file descriptor (an integer) that uniquely identifies the socket in the systen
2. Binding: A socket is bound to a port number and opti i
optionally to a specific!
address using the bind() system call. This step is n¢
: ecessary fe i
for incoming connections. ° ary for geqver sockets to lst
3. Listening (Server Sockets): Server
; r : sockets enter a listeni i
listen() system call, allowing them to accept incoming canna naresene
4. Accepting Connections (Server Sockets): ;
connections using th i
oo g the accept() system call. This call
Server sockets accept incom
blocks until a client connects
5. Connecting (Client Sockets): Clie:
using the conneet() system call. nt sockets initiate a connection to a se"LP. University-181%
t ty-IB-Pech Akash Books 2023 21
represents a server-side: socket
ket. Java supports both TCP (with Socket and
erSocket) and UDP (with Datag chet) co
versoken) munication
Socket new Socket "
- pusbeceas ket “hostname”, port OutputStream outToServer
; s Socket now ServerSocket Socketserver
InputStream — inFromClient
Socket programming allows devel
p 1g allows developer le networked applications that
can communicate with other applic the network, e
distributed systems and client-server architectures: a
CUENT SERVER
=m] fear)
| —t
[mint] open tisten
u
or
ch
' SOCKET API
IF SOCKET CLASS
en A socket is simply an endpoint for communications between the machines. The Socket
class can be used to create a socket.
he Important methods
Method Description
ng 1 public InputStreamgetInputStream() | returns the InputStream attached with
tt | this socket.
public’ OutputStreamgetOutputStream() returns the OutputStream attached with
this socket.
3 public synchronized void close() closes this socket
Us ServerSocket class
‘The ServerSocket class ¢: object is used to
an be used to create a server socket. This
Ss
establish communication with the clients.
ef Important methods
Method ~ | Description
1 public Socket acceptl) returns the socket and establish a
‘| Tonnection between server and client,
,
ce 7 public synchronized void close() | closes the server socket.— —_
si need Java Programming
semester, Advanced J
Sixth Semester
oF JAVA SOCKET PR GRAMMING
P PRO!
CKET P .
Ww ate the instance of ServerSocke ;
» need to create Served
appneation, we “ ion between the clien, 2
g866 port. number for the commune 7 be li
amber. The accep!
any other port ma eer, i returns an instance
given port number, ewe
each comm
Socket
7 —- After |
1. ServerSocket ss-new ServerSocket(6666);
accept(//establishes connection and waits for the client ae
22-2023
EXAMPLE
Creating Server
‘To create the server
cic oe we are using
a jents connects with the
for the client. Ili
2, Socke
Creating Client oe
‘Tocreate the client appliestin, we need to create the instance af Socket ©
we need to pass the IP address or hostname of the Server and a port number. 1
ost” because our server is running on same system.
are using “localhe
1. Socket s=new Socket(“localhost”,6666);
Let's sce a simple of Java socket programming where client sends a text and server
receives and prints it.
File: MyServer.java
1. import java.io.*;
2. import java.net.*;
3. public class MyServer {
4, public static void main(String|] args){
5. try
6, ServerSocket ss-new ServerSocket(6666);
7. Socket s=ss.accept();/establishes connection
8. DatalnputStream dis=new DatalnputStream(s.getInputStream()); EXAMP
‘String)dis.readUTFO; print the
text. The
9. String st
10. System.out.printin(“message= “+str);
11. ss.close();
12. jeatch(Exception e)(System.out.printin(e);}
13.)
14.)
File: MyClient,java
1. import java.io *;
2. import java.net.*;
3. public class MyClient {
4. public static void main(String|| args) {
5. tryl
6. Socket s=new Socket(“localhost”, 6666);
7. DataOutputStream dout=new DataOut
=I ataOutputSts a
8. dout.writeUTF(‘Hello Server”) a
9. dout.flush(); ae
10. dout.close();
12.LP. Univer
University-IB:Tech|-Akash Books
_ 11. s.close(); oe
het 12 Jeatehacepton ey out print)
aits, e
ai M1
© of
1 program open two c
command prompt a diplyed inthe below fare. nnn mem
After ranning the cient application, a mesa
a essaKe will be displayed on the server
ere,
ewe
EXAMPLE OF JAVA SOCKET PROGRAMMING (READ-WRITE BOTH SIDE)
In this example, client will write first to the server then server will receive and
print the text. Then server ‘will write to the client and client will receive and print the
text. The step goes on.
1. import java.net.*;
2, import java.io.*;
3. class MyServerl
4, public static void ma
5, ServerSocket ss=new ServerSocket(3333);
6. Socket s=ss.accept();
in(String args(])throws Exception{
7 DatalnputStream din-new DatalnputStream(s.getInputStream0);
t=new DataOutputStream(s.getOutputStream();
8, DataOutputStream dou
9, BufferedReader br=new BufferedReader(new InputStreamReader(System.in))
10. String str="",str’ i"
11. while(!str. equals(“stop”)){
12. str=din.readUTFO;
13, Systemout.println(“client says:
14, str2=br.readLine();
15. dout.writeUTF(str2);
16. dout.flush();
“str;ter, Advanced Java Programming
ester,
24-2023, sixth Sem
PURPO
17) »
he pury
18. din.closet):
Java apy
2 she to perfor
20. ss.close(); wre
21
1.8 JAVA DATABASE CONNECTIVITY /
; Java API that enables Java applications
‘andard interface for accessing an platform
(Structured Query Language, 2
updating, inserting applicati
Java Database Connectivity (JDBC) is a J:
interact with relational databases. It provides a sts
manipulating data stored in databases using the SQL :
JDBC allows developers to perform opevations such as querying, See
and deleting data from databases within Java applications. . statemen
Key Components of JDBC 3.Tr
1. JDBC API The JDBC API defines a set of classes and interfaces that Javi 5...)
applications use to interact with databases. The core interfaces in the JDBC API include “p,.7_°t
Connection, Statement, PreparedStatement, CallableStatement, ResultSet, etc. ae
2. JDBC Drivers: JDBC drivers are software components that provide thy 4p,
implementation for the JDBC API. There are four types of JDBC drivers: statement
+ Type 1 (JDBC-ODBC Bridge): This driver uses ODBC (Open Databas Sqr, quer
Connectivity) te connect to databases. It is platform-dependent and requires: security by
separate ODBC driver to be installed. ee
+ Type 2 (Native APU/Partially Java Driver): This driver converts JDBC database,
calls into native API calls provided by the database vendor. It requires nati This meta:
libraries specific to the database vendor. such as dat
* Type 8 (Network ProtocoV/All Java Driver): This driver uses a middlewar 6, Exe
server to translate JDBC calls into a database-independent network protocd errors that
It is purely Java-based and can be used to connect to any database for which and reliabl
middleware server is available. . database r
* Type 4 (Thin/100% Java Driver): This driver communicates directly withth 7. Por:
database server using a database-specific protocol. It is platform-independes independer
and does not require any additional software components. operating s
3. JDBC URL: A JDBC URL (Uniform Resource Locator) is a string that specie “i*20ut cod
the location of a database and the driver to use for connecting to it. It typically consis’ “M408 ens
of a protocol, database vendor-specific subprotocol, host, port, and database name Overall
Basic Steps to Use JDBC: enables Jay
1. Load the Driver: Load the JDBC eran
dri Ss )
DrraMaageteae een Ver class using Class.forName) ‘ COMPON;
2. Establish Connection:
DriverManager.getConnection(),
There are gi
Establish a connection to the database ua database.
3. Create Statement/PreparedState: cae
statement object Lo execute SQL queries, eee oe save EE ae
4, Execute SQL Queries; Use the sta " sal ire
vet eco “e stilement object to execute SQL queries #84 Package
5. Procé : Proces ace.
ee Froces the results obtained from the executed queries fo4datsbase, in
¢ Resources: Close the connect; ° :
release database resources, he — Statement, and result set bie —LP University IN Tech] Akash Books 2
PURPOSE OF JDBC
JOBE (lava Database Connectivity is to provide a standard in
ys appheations to interact with relational databases. JDRC enables Java d .
n alatabase operations seh as querying, updating, inserting, and deleting
oir Java applications. 1 serves several key purposes
1. Database Connectivity: JDBC facilitates establishing connections bets
plications and relational databases, It allows Java programs to connect
running on local or remote servers, regardless of the database vendor or
2. Data Access: DBC provides a set of classes and interfaces that enable Ja
ational databases, This includes
socuting SQL queries (SELECT statements) to retrieve data, as well as executing SQL
siatements (INSERT, UPDATE, DELETE) to modify data
8. Transaction Management: JDBC supports transaction management, allowing
siivations to aeeess and manipulate data stored
al plications to execute database operations within transaction boundaries
le sac nsure data integrity by either committing all changes as a single atomic
olling back changes if an error occur’
. 4. Prepared Statements and Stored Procedures: JDBC supports prepared
nents and callable statements, which allow developers to execute parameterized
se| SQL queries and stored procedures, respectively. This improves performance and
a) security by precompiling SQL statements and reducing the risk of SQL injection attacks
. Metadata Access: JDBC provides methods to retrieve metadata about the
tabase. such as information about tables, columns, indexes, and database schema.
's metadata can be used to dynamically generate SQL queries or for other purposes
such as data validation.
re! 6. Exception Handling: JDBC includes exception handling mechanisms to handle
J], errors that may occur during database operations. This helps developers write robust
liable code by gracefully handling exceptions and ensuring proper cleanup of
abase resources.
re 7. Portability and Platform Independence: JDBC is designed to be platform-
nt independent and vendor-neutral, allowing Java applications to be deployed on various
operating systems and connect to different database management systems (DBMS)
without code modifications. JDBC drivers provided by database vendors or third-party
te) vendors ensure compatibility with specific databases,
Overall, the purpose of JDBC is to provide a powerful and standardized APT that
enables Java applications to seamlessly interact with relational databases, enabling
data-driven functionality and database integration in Java applications.
“| COMPONENTS OF JDBC
ig There are generally four main components of JDBC through which it can interact with
4 database. They are as mentioned below:
1. JDBC API: It provides various methods and interfaces for easy communication
with the database. It provides two packages as follows, which contain the java SE and
4, iv EE platforms to exhibit WORAtwrite once run anywhere) capabilities. The java,
Y
| Sal package contains interfaces and classes of JDBC APL
java.sql: This package provides APIs for data acce:
¥| database, included in
t Java Standard Edition Gava SE)
and data process in a relationalggramminks
ed Java Pro!
ackage bY Providing
Advane
ginth Semester of java Pi
s oling with a dat,
ackage extends po statement pooling T
This Pa hin ‘connection Ps API stands for
en We allows differen
juded in. _ s methods and d.
saition Gave BE) nt application,
java Enterprise Fal ‘ 7 to connect a database to aclient @PP' vvapatication' component, 5
seo provides a stand vific driver i” gether, allow
Tae manager: It 103 : pecific call tothe own applicatio
2, JDBC Driver meta database details. APIs
catablish a connection WD A von, services to int
ser request Jn as insertion, deletion, rs
igcess the
(sud
sed to vest the operation
m8 JDBC DRIV
Gatabase to PT
tothe database. This
> Test suite:
3. soBe T ‘a by JDBC Drivers
capdation) being pertOrmes w
on BC-ODBC Drivers Teconsets database) er “males use ‘of the JDBC dri
fee sce JDBC method call to the SBE Fonction call Te maKeS Ter sies. server) ae
tage translates the JDBC Met a native library €0 088° Oot understand. 1
sun,jdbe.odbe package which ine a
‘ype
i DBC
Architecture of JI 2 Type 2
appicaton 3. Type-
(uava servlet, applet et) ea
1 Interfac:
A list of p
soc API © Driver
* Connect
: * Statem
a * Prepare
s08¢ Driver Monager * Callabl
* Results
{JDBC Drivers * Results
* Databa
+ RowSe
Classes
Description: at of |
fan * Driver
= “Application: It is a java applet or a servlet that communicates with a dab + Blob dl
5 * Clob al
a an ae a APLallows Java programs to execute SQL statemet® _—_* Types
rnd retrieve results. Some of the imy ‘
an aan portant classes and interfaces defined in JDBC" WORKING
‘i JDBC
3, DriverManager: It plays a t
= It plays an : cae
databases. fectively connect enterprise applications Omstegn
4. SDBC drivers: To communicate with a dat: Here's |
source through JDBC, you
1. Load
JDBC driver that intelli
lige
igently communicates with the respective di 7 ri
‘ive data source: latabase di
fase
memory andrate with each other. APIs define the
nteract with a particular software
different sofware aysterns
lity of existing ayate
Jerlying ende or imple
JDBC DRIVERS
API (Application Programming
cessing relational databases from
with databases such as MySQL
Here's how JDBC works in a typical scenario
ng JDBC is to load the appropriate
4 Thi
1. Leading the Driver: The
Class.forNamet) me
the DriverManager.
loads the driver classSixth Semester, “°° a connection to th,
ver is :
2 Once the driv" tT anection() Meth Py
word if required
mnnectio
oye the DriverManager Be
th the username and pa er. eee
‘ onn , a St b
esta Ne the Connection object. Thi
+t the database.
2, Establishing a ©
ablished using
the URL ofthe database, a10n8 8
i t: After
3, Creating a Statement?
is coisa using the createStatement() me aan
Statement object is used to execute SQL queries eal Sn SER, uppate
ccuti jes: SQL queries such as UPDATE
peut Bxcenting, Queries eng the exe er or pate
inethads of the Statement object. The ‘executeQuery() met pd i A er
Gueries that return a result set, while the executeUpdate
types of queries that modify the database
turns a result set, it ca
n be processed using
5. Processing Results: If the query re
methods such as next(), getStringO, getintO, ete.,of the ResultSet object returned by
sree aveeuteQuery() method. These methods allow you to iterate over the rows of the
result set and retrieve values from each column.
6. Closing Resources: After the database operations are complete, it’s important
to close the resources properly to release database connections and other resources.
This includes closing the ResultSet, Statement, and Connection objects using their
close() methods.
What is the need of JDBC?
JDBC is a Java database API used for making connection between java applications
with various databases. Basically, JDBC used. for establishing stable database connection
with the application API. To execute and process relational database queries (SQL or
Oracle queries), multiple application can connect to different types of databases which
supports both standard (SE) and enterprise (EE) edition of java.
ESTABLISHING A CONNECTION
Before Establishing JDBC Connection in Java (the front end i.e your Java Program
and the back end ie the database) we should learn what precisely a JDBC is and why
it came into existence. Now let us discuss what exactly JDBC stands for and will ease
out with the help of real-life illustration to get it working.
Java Database Connectivity (JDBC) is defined as a set of java classes and method:
to interface with database. It al: i :
databases, Iso provides uniform access to a wide range of relational
database is es
We can use JDBC call: i ;
‘JDBC calls to retrieve and update information from a database usin!
This involves the follo g functions:
(a) Opening and establish a datab: i
ase conn
(b) Send SQL statements a
(c) Process the returned result set. ,
(d) Close the database connection,
JDBC provides a databi :
: ase programmi
cannotdirectly com: i eee ;
Sipe aly eommunicate withthe ODBC driver Sun Microsc s eroe
ODBC bi slate JDBC to ODBC. There are severe ven ane
é veral type of JDBC driv
; JDBC-ODBC bridgesODBC driver
: a API partly java Driver
IDBC-Net pure java driver
4 Native protocol pure java driver
r.
JA3-29
Gap >
Why JDBC Come into Existence?
As previously told JDBC is an advancement for ODBC, ODBC being platform
dependent had a lot of drawbacks. ODBC API was written in C, C++, Python, and
Core Java and as we know above languages (except Java and some part of Python )
are platform-dependent. Therefore to remove dependence, JDBC was developed by a
database vendor which consisted of classes and interfaces written in Java.
Steps to Connect Java Application with Database
Below are the steps that explains how to connect to Database in Java:
Step1: Import_the Packages
‘Step2: Load_the_drivers using the forName() method
‘Step3: Register the drivers using DriverManager
Step4: Establish a connection using the Connection class object
Step5: Create statement
Step6: Execute the query
Step7: Close the connections
JAVA DATABASE CONNECTIVITY
Java Database Connectivity
2 Lewd Detabeve Oar 2. Oaabase Dover
rem) mee)
2-Asor Mamet) | 2.B.geteonnectiond T seancoonectiond
ereatestatementd “AaSELECT :executeaven)
(comecson }————»(_ severe)» (seve)
I fi | s.clese)
5. close() 5. close()
ata
-
‘temrveoare!
cae
eevndte :
intamming
a Progr
camester, Advanced Jav .
— table code 10 ills,
ue rating by wHting ©
tops in brief before impleme'
Me eens for DBC
conned IO
step 1: impor" .
f ve jster it before us
sen nt vesirst need to 1oad {Me driver or ro ert efor
Iv ier to ben on sto be dome or in your prost :
orprogramn, Registration ia : :
ahs the pe rwo ways mentions pelow as follow:
ine ef y time. No need of us
into memory at the Tun net of
Toad the driver's class file te Named t0
drive lowing example uses C165
Here we
new or create objects
Tower as shown below as follows
Class forNameCoracle,jdbe driver:
2. DriverManager.registerDriver’)
Step 3: Establish a connection using the
“After loading the driver, establish conne
riverManager: getConnection(url,user,password)
«user: Username from which your SQLs vommand prompt ean be accessed.
+ password: password from which the SQl- command p!
cron: [tis a reference to the Connection interface
1r which is created
+ Url: Uniform Resource Locato
String url = *jabccoracle:thin:@localhost:1521:xe"
Step 4: Create a statement
Once a connection is established you can
sppcStatement, CallableStatement, and Prepar.
sthods that enable you to send SQL commands and receive
Use of JDBC Statement is as follows
Statement st = con.createStatement0);
Note: Here, con is a reference to Connection interface used in previous step
Step 5: Execute ‘he query
ear naimes th at inportant par eesting the query. The query here
pie an have multiple types of queries. Some of them ar
* The Anserti
* Te quer for updatingnserting a table ina database
\¢ query for retrieving data. °
* The executeQuery() method
; z of the Sta
of retrieving values fom the database Te ea ec
ae Used to get all the record ofa table no Uns the object of ResultS#!
he exceuteUpdatetsql quer
import java.io;
import java.sql.*;
classGRG (
OracleDriver");
Connection class object
ctions as shown below as follows
Connection con =
rompt can be accessed.
as shown below:
interact with the database. 1
edStatement interfaces define
data from your data:
Public static void main(Stringt} ai rows Exception
rd main(String!) args) thy pt
's Exes
String url
st
st
o
)
Outpu
Step ¢
So fin:
of complet
will be clo.
close the ¢
con.cl
I Sav:
MImp
impo
Wimp
impo
1 Mai
class!
mW
pul
(
Wl
y
sLP. University-B:Tech|-Akash Books 2023-31
__> ddbe:mysql:MMocathost:3306/table_name”; // table details
String username = “rootgg"; // MySQL credentials
String password = “gfg123"
String query
= “select “from students”; // query to be run
Class.forName(
“com.mysql.cj.jdbe.Driver”); // Driver name
Conneetion con = DriverManager.getConnection(
d url, username, password);
System.out.printin(
| “Connection Established successfully”);
Statement st = con.createStatement();
ResultSet rs
= st.executeQuery(query); // Execute query
rs.next0;
| String name
= rs.getString(“name”);// Retrieve name from db
| System.out.println(name);// Print result on console
st.close(; // close statement
con.close(); close connection
System.out.printIn(‘Connection Closed...”);
}
Output:
Step 6: Closing the connections
So finally we have sent the data to the specified location and now we are on the verge
of completing our task. By closing the connection, objects of Statement and ResultSet
will be closed automatically. The close() method of the Connection interface is used to
is close the connection. It is shown below as follows:
rel con.close();
| 1/ Java Program to Establish Connection in JDBC
// Importing database
import java.sql.*;
er / Importing required classes
tY impor tjava.util.%;
1 Main class
oi classMain (
1 Main driver method
public static void main(String all)
(
| J Creating the connection using Oracle DB.
1/ Note: url syntax is standard, so do grasp
= “jdbe:oracle:thin:@localhost:1521:xe";si aq Java Proer
in Semester Advanced J°
sixth Semester
“ ecess DB
= and password 10 access DI
ion.
jj username
jy custom initial
String name
System.out-PF
cll = knextInt0
intr :
arent out prinnirenter class)
String cls = k.next0;
7 inserting data using SQL query .
String sql = “insert into student values(”+ name
ete roll 1.74 ls + °)"5
1/ Connection class object
Connection con = null;
|/ Try block to check for ‘exceptions
tryl
1/ Registering drivers
DriverManager. registerDriver(
‘neworacle jdbe,OracleDriver();
1 Reference to connection interface
don = DriverManager.getConnection(url, user,
pass);
// Creating a statement
Statement st = con.createStatement();
// Executing query
intm = st.executeUpdate(sql);
iftm == 1)
System.out. println(
“inserted successfully : “+ sql);
else
System out.printin(“insertion failed”);
1/ Closing the connections
con.elosel);
1 Catch block to handle exceptions
cateh(Exception ex) (
4 Display message when exceptions occu
ystem.err.printIn(ex); "
E:\>javae Main, java
enter
4
enter
Ga
inser
E:\>
Implem:
‘The java
IDB
with a
Clas
Clas:
Clas:
with. Thi
the java
mysql.c
to suppl
databasi
One
Prepar:
explaine
Wh
of the a
applicat
authent
for deta
Not
Au
met:
fe
Passwor
2.17
elsewhe
3."
Jdbe:my
Not
empty sLP. University-IB:Tech|-Akash Books 2023-33
SIAVA Main
enter name
Abe
enter roll no
4
enter cl
6a
inserted successfully : insert into student 1 values (*Abe* , 14, *6a")
E:\>
Implementing Server
‘The java.sql.Driver class acts as a pass-through driver by forwarding
IDBC requests to the real database JDBC Driver. The JDBC driver class is loaded
with a call to
Class.forName(drivername). The syntax is
Class.forName(“sun jdbe.odbe.JdncOdbeDriver”); or
Class forName(“oracle jdbe.driver.OracleDriver”);
When you are using JDBC outside of an application server, the DriverManager
class manages the establishment of connections.
Specify to the DriverManager which JDBC drivers to try to make Connections
with, The easiest way to do this is to use Class.forName() on the class that implements
the java.sqL.Driver interface. With MySQL Connector/J, the name of this class is com
nyaql.cj jdbe.Driver. With this method, you could use an external configuration file
ie cupply the driver class name and driver parameters to use when connecting to a
database.
Once a Connection is established, it can be used to create Statement and
PreparedStatement objects, as well as retrieve metadata about the database. This is
explained in the following sections.
When the user for the connection is unspecified, Connectorid’s implementations
of the authentication plugins use by default the name of the OS user who runs the
pplication for authentication with the MySQL server, (except when the Kerberos
aoeeatication plugin is being used; see Section 6.12.2, “Connecting Using Kerberos”
for details).
Note
‘A user name is considered unspecified only when the following conditions are all
met:
1. The method DriverManager.getConnection
password) is not used.
2. The connection property user is not used in,
elsewhere.
3, The user is not mentioned in
jdbemysql:Mlocalhost:3306/test, or jdbe
Notice if (1) or (2) is not true and an emply s!
‘ot considered unspecified.
(String url, String user, String
for example, the connection URL,or
the authority of the connection URL, as in
mysql:/@localhost:3306/test.
tring is passed, the user name is an
empty string then, and is mProgramming
semester ‘Advanced J
, sixth 5
sn 2028
r RCTION and a database It helps ty, Init
MAKING URE € CONNEC potween a Java application nd tomove th
catnblish 3 ern interface ix a factory of Statemel, get the object of Statement me
vatcteMetabata eo Feat can ee Ger transctn or
oa saaboseActnData, The Connect ior interface provide many T™tjonfsolation®), ete cu
aan mentent Hk 10), rollback), setAutol ommit0), 5 Ting queries By d
setnngement Fike commits ar executi ao
Hie default, connection commits (he chenee after opaas a
aesermony wsed methods of Connection interlace at can b
: Hee ever weates a statement object thatean Pe passing
1) public Statement ereateStatement(s crea" asta Dee.
ised to execute SQL queries | et
Ios pablie Statement ereate Statement Gant result Set Type, int result Set 1-Sta
Coneurreney): Creates a Statement object that ‘will generate Result Set objects wit! 2
the given type and concurrency. Exam
(3) public void setAutoCommit(boolean status): is used to set the commit ae
status, By default, itis true fe
im
(4) public void commit(: saves the changes made since the previous commit/ a
rollback is permanent. a
(5) public void rollback(): Drops all changes made since the previous commit/ 3. pu
rollback. 4. Cla
(6) public void close(): closes the connection and Releases a JDBC resources 5. Co!
immediately ost: 1521
Lots see the simple example of Statement interface to insert, update and delete | 6. Sta
the record resultSet
1. import java.sql.*; 7. Res
2. class FetchRecordl 8. lige
5. puble state void main(String argsfDthrows Exception| 9.rs.a
4, Class forName(“oracle jdbe.driver. OracleDriver”); 10. Sy
5, Connection con=Dri hee
Ce eo ee iverManager.getConnection(“jdbc:oracle:thin@ 11. co:
: : Q 12,
6, Statement stmt=con.createStatement(); oH
; Exam
st KECK (iy Fi
8, stmt executeUpdate(“insert into emp765 values(33,"Irfan’, : oie
9.//int result=stmt.executeUpdate(“updat fa ,"Irfan’,50000)”); 1. crea
late emp765 s ;
where id=33" 765 set name="Vimal’salary=10000 Now ir
10. int result=stmtexes c i
0 {mt executeUpdate(“delete from emp765 where id=33” Limp
11, System.out.printIn(result+” records affected”): ere id=33"); 2. clas
12, con.closel); g 3. pub
13.) 4. try|
Working a Resultet: When a data base query 5. Clas
rereturned as 4 table of data ani: ery is
nett Bot interface meade Fdata organized aecordin en ee rece ote 531 Com
esultSet i : ess tothe table data, = *? FOWS and columns. THT: Xe”
Prep
8. stmt
fp“Ips to
t, and
lement
saction
al), ete,
S.
t can be
sult Set
ects with,
e commit
. commit!
commit/
esources
d delete
e:thin:@
=10000
one
ee —— =
LP. University- 18 teen 2023-35
intially the rao th, Positioned before the fl s on
ing theBetXXKO methods, the XXX fe eheaess the data from the Resultset sean
aii datatype o
The object of ResultSet m,
cursor points to before the
of the parameter such as String,
‘aintains a cursop
first an “UFSOr pointing to a row of a table.
By default, ResultSet object
Peas vet can be moved forward only and it is not
But we can make this object to
posing either TYPE SCROLL, ty
createStatement(int,int) method as
1. Statement stmt
Initially
move for
‘SENSITIVE,
wellas we
rward and backward direction by
or TYPE SCROLL SENSITIVE in
can make this object as updatable by.
con create Statement Result Set. TYPE_SCROLL. IN
2 ResultSet CONCUR_UPDATABLE),
Example of Scrollable ResultSet
Let's see the simple example of Results
1. import java.sql.*;
2. class FetchRecord{
5. public static void main(String args[))throws Exception(
4. Class.forName(“oracle jdbe driver. OracleDriver”):
5. Connection con = Driver Ma:
nager.get Connection (“jdbc : oracle : thin : @local
est: 1521 : xe”,"system”,"oracle”);
6.Statement stmt = con.create Stat
sultSet. CONCUR_UPDATABLE);
- ResultSet rs=stmt.executeQuery(“select * from emp765");
8. getting the record of 3rd row
9. rs.absolute(3);
10. System.out printIn(rs.getString(1)+” “+rs.getString(2)+” “trs.getString(3)):
11. con.close();
12.})
Example of PreparedStatement interface that inserts the record
First of all create table as given below:
1. create table emp(id number(10),name varchar2(50));
Now insert records in this table by the code given below:
tement (Result Set.TYPE_SCROLL_SENSITIVE.
1. import java.sql.*;
2. class InsertPrepared(
4. public static void main(String args)){
4. try| .
5. Class.forName(“oracle,jdbe.driver.OracleDriver”); a
6. Connection con = Driver Manager.get Connection (“jdbe : oracle : thin :@localhost
ction con =
1: 0 oracle”); ; _
1 Prepared = ‘stmt=con.prepareStatement(“insert into Emp values(?,?)";
redStatement stmt= ‘hee
8. stmt.setint(1,101)//1 specifies the first parameter in the query36-2023
9, stmt.setString?,
Updates
execute!
» records inse!
10. int i=stmt sted’
11, System.out.printInG+
12. con.closel)s On
13 Jeateh(Fxception e)t System-out printl
M4
15.1
6.) rd
ae of PreparedStatement interface that updates the bane
1. PreparedStatement stmt=con. prepareStatement( ‘update emp
id=?");
2. stmt. setString(1,"Son00")//1 spec
3. stmt.setInt(2,101);
4. int i=stmt.executeUpdate();
5, System.out.printIn(i+” records updated”);
Example of PreparedStatement interfac
1. PreparedStatement stmt=con.prepareStatement(
2. stmt.setInt(1,101);
3.
4, int iestmt executeUpdate);
5, System.out.printIn(i+” records deleted”);
Example of PreparedStatement interface that retrieve the records ¢
table
1. PreparedStatement stmt=con.prepareStatement(“select * from emp”);
2, ResultSet rs=stmt.executeQuery();
3, while(rs.next)){
4, System.out.println(rs.getInt(1)+” “+rs.getString(2));
et name=? Why
cifies the first parameter in the query ie. na
.e that deletes the record
“delete from emp where id=
Example of Pre} i
: oe to insert records until user press n
2. import java.io.*;
3. class RS{
4. publie static voi
main(String args{))thro
am ratio ve ws Excepti
5, Class forName(“oracle jdbe.driver.OracleDriver”) “me
6. Connection eon = Driver Manager. get Connection (
host:1521:xe”,”system”,"oracle”); ~onnection (“idbe : oracle : thin
7. PreparedStatement ps=con,
‘=con-prepareStatement(“insert; ’,
8, BufferedReader br=new BufferedReaden(n, Tones noms valu
' ew InputStreamReader(Syste”
10. dol
system.out.printin enter id”);2
13.
14
15,
16.
7.
18,
19.
20.
21
22.
23.
24.
25.
26,
21.
28,
29.
30.
31
EP. University-1B techy
Ber-parselnt(br.readLine())
System.out.printin(“enter name."
String name=br.read]
Akash Books
int id=Intey
LineQ);
System.out.printin(enter sal,
lary:”);
float sal;
‘ary=Float.parseFloat(br.readLine();
ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.printIn(i+” records affected”);
System.out.printin(“Do you want to continue: y/n”),
String s=br.readLine();
iffs.startsWith(“n”))|
break;
)
Iwhile(true);
con.close();
v
202:ing
wa Programmint
sixth Semester, ‘Advanced Java
38-2028 ix 7
unit - 1 :
‘ACE
A INTERF:
eee wn from the data.
ein rene -an get further informatio! im x a
morn on an e table like total number of cota Sea
Common!
[Method
public int
SQLException
public String getColumnName(int index)
throws SQLException
public String getColumnTypeNametint
index)throws SQLException
public String getTableName(int index)
throws SQLException
How to get the object of ResultSetMetaData:
The getMetaData() method of ResultSet interface returns the object
ResultSetMetaData. Syntax:
1. public ResultSetMetaData getMetaData()throws SQLException
Example of ResultSetMetaDatainterface :
1. import java.sql.*;
class Rsmd{
public static void main(String args{)){
try!
Class.forName(“oracle jdbe.driver. OracleDriver”);
Connection con=DriverManager.getConnection(
“jdbe:oracle:thin:@localhost:1521:xe”,/"system”,"oracle”);
PreparedStatement ps=con.prepareStatement{“select * from emp”)
9. ResultSet rs=ps.executeQuery(); °
10. ResultSetMetaData rsmd=rs.getMetaData();
11. System out printIn(“Total columns: “+rsmd.getColum:
12, System.out.printn(“Column Name of 1st column: “4
18, Systemoutprintin(‘Column Type
getColumn TypeName());
14, con.closel);
15, Jeatch( Exception
16.)
17.4
Output: Total columns: 2
Column Name of Ist column: ID
Column Type Name of Ist column: NUMBER
used methods of ResultSet
Description
it returns the total num!
the ResultSet object.
itreturns the column name of thes
column index.
it returns the column type name for the
specified index.
it returns the table name for the specified
column index. .
per of eolumns in
{gotColumnCount(}throws
ecified
of
nCount());
rsmd.getColumnName(1))
Name of 1st
column: “4rsmd
System.out.printin(e);)
g. da
Java
iris ada
1M
2. It
3. All
Illus
Asim
HW Jaw
Wsteu
publi
pri
pul
th
1
pul
Setter and
Prope
Litst
2. The
3. The
4. Itst
Prope
L It sh
2. The
we have to
3. The,
4. It sh
5. Jax
6.//get
7. publ
8. pr
9.
10. p
uy
Ry
13.
14.
165,
16.
17.)2023-39
saw that enca
ap a capsulate:
jpisa dave class that should follow the fot
1, Must implement Serializable
2. tshould have a public nowarg construc
nstructor
3.All properties in java bean m
: A ‘an must be priva
illustration of Javaliean Cian he with publicge
ple example of JavaBean Class
Java program to illustrate the
y structure of JavaBean class
public class TestBean (
Many objects into
a single object (the bean) oe
lowing conventions: A
tters and setter methods :
is mentioned below:
private String name;
public void setName(String name) {
this.name = name;
b
public String getName() ( returnname; |
2.2 SETTER AND GETTER METHODS IN JAVA
Setter and Getter Methods in Java properties are mentioned below:
Properties for setter methods:
1. It should be public in nature.
2. The return type a should be void.
3. The setter method should be prefixed with the set.
4, It should take some argument i.e. it should not be a no-arg method.
Properties for getter methods:
1 It should be public in nature.
-2, The return type should not be void i.e. according to our requirement, return type
wehave to give the return type.
3. The getter method should be prefixed with get.
4. It should not take any argument.
5./ Java program to illustrate the
6. / getName() method on boolean type attribute
1. public classTest {
8. private boolean empty:
9.
10. public boolean getName)!
1. return empty;
ana}
13.
14. public boolean isempty0l
15. return empty;
6.)
17.)ming.
1 gava Program?
ar, Advanced
40 2028 sixth Semester: M
Bxample of JavaBean CHS
Hxample 1 awa C18
Fea implementation ofthe! H
Fara Program of dawaBBean cls
eae serializable |
Public clase Student implements l=" io.Seri
te int id:
private String ®
1 Constructor
public Student (}
Setter for Id
public void setId
11 Getter for Id
public int getld0 (return id; }
1 Setter for Name
public void setNamel
1/ Getter for Name
public String getName)
(intid) ( this.id = id)
(String name) (this.name = name; |
{ returnname; }
2.3 CREATION OF JAVABEAN
Creation process of a java bean:
1. Create a class in a package as the bean class.
2 Provide the required variables as the properties.
3. Provide setter and getter methods for each of the variables.
44 Store the package folder inside a classes folder.
5. Compile the file as ordinary java file.
PROPERTIES OF JAVABEANS
AdiavaBean property i named feature that can be accessed by the user of the objec
The feature cn be of ny Java data type, containing the classes that you define.
JavaBean property may be read, write, read-only, or write-only. JavaB ;
aeaoet through two methods in the avaBean's implementation class: ay
(a) getPropertyName ()
For example, if the property name is firstN:
lame,
getFirstNamel) to read that property. This method is wlan eee sp eaamet
(b) setPropertyName () ie Becessor.
For example, if the property name is fi
; is firstName,
setFirstName() to write that proper ame, the method *
property. This method is ealled the mesa
‘TYPES OF JAVA BEANS mutator.
yypes of beans in java:
1, Session Beans, it is also sub divid
ide into tw
i) Statel wion beans .
(ii) Stateful Session Beans
2. Entity Beans
serve?
for the
ths
gata.
infor™
cone’
types ©
recon!
destroy
to java
servlet
Java ¢
such a
web ap
known
Th
a
class 01
to proc
2.
compo
of serv
init0, s
Popula
ey
within
and ot
among
4.
contain
The se;
using t
5.
configu
Ph
ea
the serLp.
Driven Be,
Session Bean is,
2023-41
cqor session. The function
eo the client. This bean ¢,
1 is only for the
is ignal client
iis may & SvsteM crash egy TM SAEtional, egy tUlations oF datahase access
ia. The stateless Session Beane (out ts object a i8 Not recoverable and due
Smal state; only allow paraitey a Sistributed gpa,” MANAKE its own unrelenting
ection with informal state, bag Neect which has no connection with
cut are called Entity Bean sy eae
ateful Session Bean has a
“l to the customer. The second.
mase the unrelenting data. It is
‘| by entity bean crashes, it will
Session bean, except it responds
? and its famen so YeY,
mized by a main key, it the soy
roy the remote reference Meve,
i java miossage Service, os
limites
2.4 SERVL
ET
sunlet architecture refers to the degiey eCHITECTURE
jaa classes that dynamically process and na, uucture of
such as web browser or mobile devices, Servlets 4 to requ
sebapplications and are part of th are'comi
| town as Jakarta BE. © Java Enterprise Editi
Java Servlets, which are
lests made by web clients,
imonly used for developing
ion (Java EE) platform, now
The servlet architecture typically involves the follow
ae components
] _ 1 Bervint laens Ts fas dna cian jitters ora in Thin
jas or implements the javax.servlet Servlet interface & ein ie bets
viet classes contaii ic
‘nprocess client requests and generate responses classes contain the logi
2, Servlet Container: Also known as a servlet engine or servlet runtime, this is a
component of the web server or application server responsible for managing the lifecycle
rviets. The servlet container loads servlet classes, initializes them, invokes their
‘iti, service(), and destroy() methods as appropriate, and manages their concurrency.
Popular servlet containers include Apache Tomcat, Jetty, and IBM WebSphere.
3. Servlet Context: The Servlet Context represents the servlet’s environment
rihin the servlet container. It provides access to configuration parameters, resources,
sbject. | other servlets within the same web application, The Servlet Context is shared
a fine. A | “aga servlets within the same web application.
‘ures are, 4 Servlet Request and Response: These are ohjects provided by ae
iner to encapsulate the client's request and the servle's Por ent
hue servlet processes the request, generates the response, and sencs \
‘sing these objects. i Servlets are typically
"Deployment Descriptor (neha a ache me
‘“ppings, initialization parameters, and other co AUT Gs servlets directly in
‘annotations (@WebServlet, @WeblnitParam
“servlet class. a
6. ing: Servlets are mappet "8
‘gly, URL Mapping: Servlets tr tons, When a client wr
jpr2ment descriptor or via an ‘yest to the appror'
ththe servlet container routes the 104
“Shing
vould be
would *)
ogin) in the
terns (e.8., Mello, login
0 UR pin sands request to 2 specitic
te servlet based on its
2 clients send
4 model, where client
ere pnses that are sent
; fc the reqves generate resp0 taro sent
waite architecture follows | he est " i pa
S to servlets, which proce! aia
the cients, This architectU
oy
ev