0% found this document useful (0 votes)
2 views

Advanced Programming-2 (1)

The document provides an overview of Java programming, including its key features, data types, variables, and control structures. It also covers Java applets, their execution, and differences from Java applications, as well as an introduction to JavaFX for GUI development. Key concepts such as variable types, decision-making statements, and looping structures are discussed in detail.

Uploaded by

alazarjesus4
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Advanced Programming-2 (1)

The document provides an overview of Java programming, including its key features, data types, variables, and control structures. It also covers Java applets, their execution, and differences from Java applications, as well as an introduction to JavaFX for GUI development. Key concepts such as variable types, decision-making statements, and looping structures are discussed in detail.

Uploaded by

alazarjesus4
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 97

1

ADMAS UNIVERSITY
INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE

Advanced Java programming


((CoSc3053)
2

CHAPTER-ONE

Overview of Java Programming


Why you need to learn ?
 Java is the top most programming language
 Very(extremely) flexible (web apps, android apps,
game app, business apps)
 Easy to find a job as a developer

4

 Java is a high-level programming language.


 originally developed by Sun Microsystems and released in 1995.
 Java runs on a variety of platforms, such as Windows, Mac OS, and
the various versions of UNIX.
Key features of java are:
• Object Oriented
• Platform Independent
• Simple
• Secure
• Architecture-neutral
• Portable
• Robust
Data type and Variables
 Data type is the classification of data.
 Tells the compiler how the programmer intends to use
the data.
 specify the different sizes and values that can be stored
in the variable.
 There are two types of data types in Java:
1. Primitive data types
2. Reference/Object Data Types:
……
Primitive data type
 Predefined by the language and named by a keyword.
 Include boolean, char, byte, short, int, long, float and double.

Referenced data type


 Contains reference/address of dynamically created objects.
 Include Classes, Interfaces, and Arrays.
 To declare a variable using a reference type, you simply list the
class name as the data type.
 For example, the following statement defines a variable that can
reference objects created from a class named Ball:
Class Ball{
Ball b;
}
….
// Reference/object data type example
public class RefDataType {
public static void main(String[]args)//
{
demo d = new demo();//d is reference data type
d.display();
}
}
class demo{//class
public void display() //method
{
System.out.println("this is an example of
reference data type ");
}
}
Variable
A variable is a container for information you want to
store.
 variable provides us with named storage that our
programs can manipulate.
 Each variable in Java has a specific type, which
determines :
 the size and layout of the variable's memory;
 the range of values that can be stored within that
memory; and
 the set of operations that can be applied to the variable
….
 All variables have two important attributes:
A type
which is established when the variable is defined
(e.g., int, float, char).
 A value
which can be changed by assigning a new value to the
variable
The kind of values a variable can assume depends on
its type.
 For example, an integer variable can only take
integer values (e.g., 2, 100, -12).
Valid variables /identifiers
A valid identifier is a sequence of one or more letters,
digits or underscores characters (_).
 Neither spaces nor punctuation marks or symbols can
be part of an identifier.
 Only letters, digits and underscore characters are valid.
 In addition, variable identifiers always have to begin
with a letter or underscore (_).
 In no case they can begin with a digit.
 They cannot match many keyword of the java
language.
…..
 syntax:
data type variable_Name = value;
(value is optional because in java, we can accept the
value from the keyboard. )
 The following are valid examples of variable declaration
and initialization in Java: -
 int a, b, c; // Declares three ints, a, b, and c.
 int a = 10, b = 10; // Example of initialization
 double pi = 3.14159; // declares and assigns a value of pi.
 char a = 'a'; // the char variable a is initialized with value
‘a’.
Types of Variables
 There are three kinds of variables in Java: -
1. Local variables
2. Instance variables
3. Class/Static variables
 Local
Variables: declared inside a method body, block or
constructor. It means variable is only accessible inside the
method, block or constructor that declared it.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method,
constructor, or block.
 Local variables are implemented at stack level internally.
 Default values are not assigned to local variables in Java.

Example:
for(int i =0;i<10;i++)
Instance variable
 Created when object is created(with “new ”keyword),
destroyed when object is destroyed.
 Access modifier can be used(else default access
modifier is used).
 Initialization is not allowed for the instance variable.
Static variable
Decision and Repetition statement
 The decision and repetition statements manage the
flow of execution in a program.
 Decision making structures have one or more
conditions to be evaluated or tested by the program.
 Java programming language provides following types of
decision making statements.
1. conditional statement
2. switch statement
Conditional statement If
 An if statement consists of a Boolean expression followed by
one or more statements.
 Syntax: if (condition) Statement1;
 Note:
 A statement may be simple, block or null statement.
 The” if” keyword is used to execute a statement or block only if
a condition is fulfilled.
 Where condition is the expression that is being evaluated.
 If this condition is true, statement under the” if” clause will be
executed.
 If it is false, the first set of code after the end of the if statement
will be executed.
Conditional structure: if..else
 An if else statement in programming is a conditional
statement that runs a different set of statements
depending on whether an expression is true or false.
 Syntax: if (condition)
Statement1;
Example
else
Statement2;
if (x == 100)
System.out.print ("x is 100");
else
System.out.print ("x is not 100");
Nested if statement
You can use one if or else if statement inside another if or
else if statement(s).
Syntax
if(condition 1) {
statements;
if(condition 2) {
statements;
}
}
Switch statement
A switch statement allows a variable to be tested for
equality against a list of values. Each value is called a
switch (operator) {
case, and the variable being switched on is checked for
case '+’:
each case.
switch(expression) { result = operand1 + operand2;
break;
 Syntax case constant 1 :
case '-’:
Statements; result = operand1 - operand2;
break; // optional break;
case constant 2: case '*’:
Statements; result = operand1 * operand2;
break; // optional break;
… case '/’:
default: // Optional result = operand1 / operand2;
Statements; break;
default: System.out.println
}
("unknown operator ");
break; }
Iterative statement(Loop)
 A loop statement allows us to execute a statement or
group of statements multiple times.
 Java programming language provides the following
types of loop to handle looping requirements.
 while loop
 do-while loop
 for loop
While loop
 While loop executes a set of statements as long as the
condition specified at the beginning is true.
 The condition is evaluated at the beginning of the loop.

Example
while (condition) {
statement1; int x = 10;
… while( x < =20 )
statement n; { System.out.print("valu
} e of x : " + x ); x++;
}
do…while loop
A do-while loop is similar to while loop except the
condition is at the end of the loop.
 As a result, the loop always executed at least once,
regardless of whether the condition is true or not.

do { int x = 10;
Statements; do{
} System.out.print("value
of x : " + x ); x++;
while(Boolean_expr
}while( x < =20 ) ;
ession);
The for loop
 The for statement (also called for loop) is similar to the
while statement, but has two additional components: an
expression which is evaluated only once before everything
else, and an expression which is evaluated once at the end
of each iteration.
 Syntax:

for(initialization; Boolean_expression; update)


{
Statements;
}
Arrays
 Array is a collection of similar items in a contiguous
memory.
 An item in the array is called Element.
 Dimension refers to size of the array.
 Individually referenced by adding an index instead of
declaring individual variables.
 Syntax:

dataType[] arrayName; // preferred way. or


dataType arrayName []; // works but not
preferred way.
What is JDK
29

CHAPTER 2
JAVA APPLET

By Habtamu K.
Java applet
 Typically embedded inside a web page and runs in the
context of a browser.
 Applet class provides the standard interface between
the applet and the browser environment.
 The Applet class is contained in the java.applet
package.
All applets run in a window, it is necessary to include
support for that window by importing java.awt package.
Applets are not executed by the console-based Java
run-time interpreter.
Java applet…
 Executed by either a Web browser or an applet viewer.
 Execution of an applet does not begin at main( ).
 Output to your applet’s window is not performed by
System.out.println( ).
 Rather, it is handled with various AWT methods, such
as drawString( )
 Once an applet has been compiled, it is included in an
HTML file using the APPLET tag.
The applet will be executed by a Java-enabled web
browser when it encounters the APPLET tag within the
Methods in applet class
 setBackground(Color): Sets the background
color.
setFont(Font): Sets the font of the component.
setForeground(Color): Sets the foreground color.
 show(): Shows the component.
 setColor(Color): sets the color for the image to
be drawn.
Applet Initialization and Termination
 The Applet class give the framework to build any applet:
init( ), start( ), stop( ), and destroy()
 When an applet begins, the AWT calls the following
methods, in this sequence: 1. init( ) 2. start( ) 3. paint( )
 When an applet is terminated, the following sequence of
method calls takes place: 1. stop( ) 2. destroy( )

init():-
 the first method to be called;
 used to initialize variables.
start():-
 called after init( ).
 It is also called to restart an applet after it has been stopped(i.e start() method is called
every time, the applet resumes execution).
paint():-
 The paint() method contains Graphics parameter.
 Used to redraw the applet output.
stop():-
 called when the applet is stopped(i.e for example ,when the applet is minimized the stop
method is called).
destroy():-
 called when the applet is about to terminate(the applet is completely removed from
memory).

Java Applet vs Java Application

Java Application Java Applet


stand-alone programs which can be Java programs which are designed to exist
executed independently within HTML web document
Must have main() method for them to Do not need main() for execution
execute
needs the JRE cannot run independently and require API’s

Do not need to extend any class unless Must extend java.applet.Applet class
required
Can execute codes from the local system cannot do so

Has access to all the resources available in Has access only to the browser-specific
your system services
Chapter 3

Java GUI using JAVAFX


JavaFX (stands for Java Effects)

 Here are some key points about JavaFX:


1. Purpose:
To develop websites and other applications.
It allows developers to create visually appealing UI.
2. Cross-Platform:
supports desktop computers (including Microsoft Windows, Linux, and macOS),
web browsers, and mobile devices (iOS and Android)
3. Integration with Java SE:
 Both Swing and JavaFX are included
4. Open Source:
5. Features:
 APIs for designing GUI applications,
 advanced visual effects,
 multimedia, and support for drag-and-drop installation of widgets onto the
JavaFX
 a Java library that is used to develop Desktop
applications as well as Rich Internet Applications (RIA).
 The applications built in JavaFX, can run on multiple
platforms including Web, Mobile and Desktops.
Working with JavaFX
1. Adding JavaFX extension/plugin to our IDE
2. Install scene builder
3. Create new JavaFX project.
4. Add extra widgets on the created scene
Features of JavaFX
To develop GUI Applications using Java programming
language, the programmers rely on libraries such as
Advanced Windowing Toolkit and Swings.
After the advent of JavaFX, the Java programmers can
now develop GUI applications effectively with rich
content.
Features of JavaFX
Following are some of the important features of JavaFX: -
 Written in Java: The JavaFX library is written in Java and
executed on a JVM.
 FXML: HTML like declarative markup language. The sole
purpose of this language is to define a user Interface.
 Scene Builder: an application enables users to drag and
drop design interface.
 Swing Interoperability: In a JavaFX application, you can
embed Swing content using the Swing Node class.
 Built-in UI controls: JavaFX library caters UI controls using
which we can develop a full-featured application.
Features of JavaFX
Following are some of the important features of JavaFX:
-
 CSS like Styling: JavaFX provides a CSS like styling. By
using this, you can improve the design of your
application with a simple knowledge of CSS.
 Rich set of API’s: JavaFX library provides a rich set of
API’s to develop GUI applications, 2D and 3D graphics,
etc.
JAVAFX architecture and Program
structure
Scene Graph
the starting point for constructing a JavaFX application.

It is a hierarchical tree of nodes that represents all of the


visual elements of the application's user interface.
A single element in a scene graph is called a node.

Each node has an ID, style class, and bounding volume.

The javafx.scene API allows the creation and specification


of several types of content, such as: node, state, effect
JAVAFX architecture and Program
structure
 Node
Shapes (2-D and 3-D), images, media, embedded web
browser, text, UI controls, charts, groups, and containers
 State
Transforms (positioning and orientation of nodes), visual
effects, and other visual state of the content
 Effect
Simple objects that change the appearance of scene graph
nodes, such as blurs, shadows, and color adjustment.
JAVAFX architecture and Program
structure
Java Public APIs for JavaFX Features:-These new Java APIs for
JavaFX features:
 Allow the use of powerful Java features, such as generics,
annotations, and multithreading.
 Make it easier for Web developers to use JavaFX from other
JVM-based dynamic languages, such as Groovy, and JavaScript.
 Allow Java developers to use other system languages, such as
Groovy, for writing large or complex JavaFX applications.
 Extend the Java collections library to include observable lists
and maps, which allow applications to wire user interfaces to
data models, observe changes in those data models, and
update the corresponding UI control accordingly
JAVAFX architecture and Program
structure
Graphics system
 It supports both 2-D and 3-D scene graphs
 It provides software rendering(prism, Quantum Toolkit are
examples)
Glass Windowing Toolkit
 provide native operating services(managing the windows,
timers, and surfaces.
 It serves as the platform-dependent layer that connects the
JavaFX platform to the native operating system.
JAVAFX architecture and Program
structure
Threads
Pulse
 Pulse is an event generated during action.
 throttled 60 frames per second (fps) during animation.
 Media and Images
 JavaFX supports different medias with different extension

 JavaFX media functionality is available through the


javafx.scene.mediaAPIs.
 JavaFX supports both visual and audio media (MP3, AIFF, and WAV
JAVAFX architecture and Program
structure
Web Component
 JavaFX contains WebKit, which is an open source web browser
engine that supports HTML5, CSS, JavaScript, DOM, and SVG
 It enables developers to implement the following features in
their Java applications:
 Render HTML content from local or remote URL.
 Support history and provide Back and Forward navigation.
 Reload the content.
 Apply effects to the web component.
 Edit the HTML content.
 Execute JavaScript commands.
 Handle events.
JAVAFX architecture and Program
structure
CSS
 JavaFX Cascading Style Sheets (CSS) provides the ability to apply
customized styling to the user interface of a JavaFX application
without changing any of that application's source code.
 CSS can be applied to any node in the JavaFX scene graph and are
applied to the nodes asynchronously.
 JavaFX CSS styles can also be easily assigned to the scene at
runtime, allowing an application's appearance to dynamically
change.
JAVAFX architecture and Program
structure
UI Controls
 The JavaFX UI controls available through the JavaFX API are
built by using nodes in the scene graph.
 They can take full advantage of the visually rich features of the
JavaFX platform and are portable across different platforms.
 JavaFX CSS allows for theming and skinning of the UI controls.

 These controls reside in the javafx.scene.control package.


JAVAFX layout components

 JavaFX layouts are components, which contains other components


inside them.
 The layout component manages the layout of the components
nested inside it.
 JavaFX layout components are also sometimes called parent
components because they contain child components.
javafx.scene.layout package provides various classes that represents
the layouts.

JAVAFX layout components
JAVAFX layout components

 To create a layout, you need to


 Create node. E.g.

Button playButton = new Button("Play");


 Instantiate the respective class of the required layout. E.g.

HBox hbox = new HBox();


 Set the properties of the layout. E.g.

hbox.setSpacing(10);
 Add all the created nodes to the layout. E.g.
JAVAFX layout components
UI Controls
 JavaFX controls are JavaFX components which provide some kind
of control functionality inside a JavaFX application.
 For instance, a button, radio button, table, tree etc.

 For a control to be visible it must be attached to the scene graph


of some Scene object.
 Controls are usually nested inside some JavaFX layout
component that manages the layout of controls relative to each
JAVAFX layout components
UI Controls :JavaFX contains the following controls:
 Accordion MenuBar
TabPane
 Button PasswordField
 CheckBox TextArea
ProgressBar
 ChoiceBox TextField
RadioButton
 ColorPicker TitledPane
Slider
 ComboBox ToggleButton
Spinner
 DatePicker ToolBar
 Label SplitMenuButton
TreeTableView
 ListView SplitPane
TreeView
 Menu TableView
Event Handling
 An event is occurred whenever the user interacts with the
application nodes.
 There are various sources by using which, the user can
generate the event. For example;
Use of mouse
Press any button on the keyboard
Scroll any page of the application
 Hence, we can say that the events are basically the
notifications that tell us that something has occurred at the
user's end.
 The javaFX. Event package provides the basic framework for
Event Handling
 Associated with each event is an event source, an event target, and an
event type.
 Source:
 GUI objects (e.g., a Button object) which generate an ActionEvent (e.g., when the
button is clicked)
 The source implements the EventTarget interface.
 Listener
 An object that subscribes (listens) for a particular type of event to occur. The
listener must implement an interface like EventHandler or InvalidationListener
 Type
 An additional classification that are used to specify the specific type of event. For
example, a MouseEvent has the following types: ANZ, MOUSE_CLICKED,
MOUSE_PRESSED, MOUSE_RELEASED, MOUSE_MOVED, MOUSE_DRAGGED,
MOUSE_ENTERED, MOUSE_EXITED, MOUSE_ENTERED_TARGET,
MOUSE_EXITED_TARGET, DRAG_DETECTED.
Types of events
 In general, the events are mainly classified into the following
two types.
1. Foreground Events :
 mainly occurred due to the direct interaction of the user with the
GUI of the application Such as:-
 clicking the button,
 pressing a key,
 selecting an item from the list,
 scrolling the page, etc.

2. Background Events:
 doesn't require the user's interaction with the application.
 mainly occurred to the operating system interrupts, failure,
Event handler
JavaFX facilitates us to use the Event Handlers to handle
the events generated by:-
Keyboard Actions,

Mouse Actions, and

many more source nodes.


Adding an Event Handler
 Event Handler must be registered for a node to process
the events.
 Event handler is the implementation of the
EventHandler interface.
 The handle() method of the interface contains the
logic which is executed when the event is triggered.
 To register the EventHandler, addEventHandler() is
used. In this method, two arguments are passed:
1. Event type
2. EventHandler object.
Adding an Event Handler….
The syntax of addEventHandler()
node.addEventHandler(<eventType>,new EventHandler (<eventType>() {

public void handle( e)

{ //handling code

} });
….
Shapes
 The Shape class provides definitions of common properties for objects
that represent some form of geometric shape.
 These properties include: The Paint to be applied to the fillable interior
of the shape. The Paint to be applied to stroke the outline of the
shape.
 The decorative properties of the stroke, including:
 The width of the border stroke.
 Whether the border is drawn as an exterior padding to the edges of the
shape, as an interior edging that follows the inside of the border, or as a
wide path that follows along the border straddling it equally both inside and
outside.
 Decoration styles for the joins between path segments and the unclosed
ends of paths.

….
Color
 In JavaFX, we can fill the shapes with colors.
 To apply colors to an application, JavaFX provides various
classes in the package javafx.scene.paint package.
 This package contains an abstract class called Paint and it
is the base class of all the classes that are used to apply
colors.
 These classes are:-
Color
ImagePattern
LinearGradient
RadialGradient
JavaFX Text
Color
 JavaFX library provides a class named
javafx.scene.text.Text for this purpose.
 This class provides various methods to alter various
properties of the text.
 We just need to instantiate this class to implement text
in our application.
 The properties of JavaFX Text are described in the table
below.
Chapter 4
Streams and File I/O
Introduction
 Data stored in variables and arrays is temporary.
When the variable lost/the program terminates, the data
will lost too.
 Computers store files on secondary storage devices.
 Data maintained in files is exists beyond the duration of
program execution.
Input output streams
 Stream refers to the transfer of data either to or from
a storage medium.
 Input refers to the flow of data from a file means we
can read the contents from a file with the help of Java
program.
(read data from source )
 Output refers giving some text in the java’s program
and this will write the data into the file which is
specified.
(write data to a destination).
Stream Classes
 The java.io package provides us the large number of
stream classes to perform input and output (I/O) in
Java.
 All these streams classes represent an input source and
an output destination.
 These classes are divided into groups.
1) Byte Stream Classes -- For handling the operation on
files at the byte level.
2) Character Stream Classes – For handling the operation
on files at the character level. And this Stream uses
16-bit character codes.
InputStream Classes
 used to read bytes from a file, memory or console
 Some of the subclasses of InputStream class are :
 FileInputStream.
 DataInputStream.
 BufferedInputStream.
 StringBufferInputStream and many more.

Methods inherited by InputStream subclasses:-


 read() –Used to read a byte from input stream.
 read(bytes b[]) –It reads an array of bytes into b.
 read(byte b[], int n, int m) –It reads array of byte into b those are equals
to m and must start from n.
 Skip(n) –It skips the n bytes while taking input from a file.
 reset( ) – This will Set the File Pointer to beginning of a File.
 Close( ) –For closing streams
OutputStream class
 Used to write 8-bit bytes to a stream
 subclasses of OutputStream class are
BufferedOutputStream,
ByteArrayOutputStream,
DataOutputStream,
FileOutputStream,
FilterOutputStream,
ObjectOutputStream and many more.
Chapter 5
Multithreading
Recall
Process:- a program under execution.
Threads
 lightweight process(it does not have its own resource, it
shares the process’s resource ).
 Sub –unit of a process.
Multithreaded
 multiple threads sharing a resource and running
concurrently.

A thread goes through various stages in its life cycle.
 For example, a thread is born, started, runs, and then dies.
The following diagram shows the complete life cycle of
a thread.

Java is multithreaded programming language.


Multithreading in java
Create a Thread by Implementing a Runnable Interface
You will need to follow the following 3 steps.

Step 1: implement a run () method provided by a Runnable


interface.

This method provides an entry point for the thread.

Step 2: instantiate a Thread object using a constructor.

Step 3: Once a Thread object is created, you can start it by calling


start () method, which executes a call to run () method.
Example public class mainthreadclass implements Runnable {
String tname;
public mainthreadclass(String tname) {
this.tname = tname;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(tname + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class mainmethodclass{
public static void main(String[]args){
Thread t = new Thread(new mainthreadclass("thread"));
t.start();
}
}
Chapter 6
Networking in java
Recall
Network – the interconnection between device
Socket programming
Socket –
Sockets provide an interface for programming networks
at the transport layer
Used for file i/o (stream)
Socket-based communication is independent of a
programming language used for implementing it
Socket programming
URL manipulation
URL can be broken down into parts, as follows:
protocol://host:port/path?query#ref
Example: http://www.amrood.com/index.htm?
language=en#j2se
The java.net.URL class represents a URL and has a
complete set of methods to manipulate URL in Java.
Socket programming implementation
Sockets provide the communication mechanism
between two computers using TCP.
java.net.Socket class represents a socket.
java.net.ServerSocket class provides a
mechanism for the server program to listen for
clients and establish connections with them.
Socket programming implementation
After the connections are established,
communication can occur using I/O streams.
Each socket has both an OutputStream and an
InputStream.
The client's OutputStream is connected to the
server's InputStream, and
The client's InputStream is connected to the
server's OutputStream.
RMI
Remote method invocation (RMI)
Used in distributed application (system)
allows an object to invoke methods on an object
running in another
(i.e stub object client; skeleton objectserver )
Remote method invocation (RMI)
Stub(client side)
 It initiates a connection with remote Virtual Machine
(JVM),
 It writes and transmits (marshals) the parameters to
the remote Virtual Machine (JVM),
 It waits for the result.
………
 It reads (unmarshals) the return value or exception,
and
 It finally, returns the value to the caller.
Remote method invocation (RMI)
Skeleton(server side )
 It reads(unmarshals) the parameter for the remote
method
 It invokes the method on the actual remote object, and
 It writes and transmits (marshals) the result to the
caller.
Chapter 7
Java database
connectivity
Database and SQL
Recall
 What is database?

 What is SQL?

 What is the relation between database and SQL


A database provides various functions like data security,


data integrity, data sharing, data concurrence, data
independence, data recovery etc.
However, all database management systems that are now
available in the market like Sybase, Oracle, and MS-Access
do not provide the same set of functions, though all are
meant for data management.
Almost all relational database management systems use
SQL (Structured Query Language) for data manipulation
and retrieval.
SQL is the standard language for relational database

SQL is a non-procedural language, where you need to


concentrate on what you want, not on how you get it.
Put it in other way, you need not be concerned with
procedural details. SQL Commands are divided into four
categories, depending upon what they do.
 DDL (Data Definition Language)
 DML (Data Manipulation Language)
 DCL (Data Control Language) and
 Query (Retrieving data)
JDBC programming
JDBC stands for Java Data Base Connectivity.
JDBC is a specification that provides a complete set of
interfaces that allows for portable access to an
underlying database.
Includes API in its library.
Used in:-
Making a connection to a database.
Creating and executing query statements.
Viewing & Modifying the resulting records.
JDBC programming
Java can be used to write different types of
executables, such as:
 Java Applications.
 Java Applets.
 Java Servlets.
 Java server pages (JSP)
 Java enterprise edition (JEE)
All of these different executables are able to use a JDBC
driver to access a database, and take advantage of the
stored data.
JDBC components

Driver: This interface handles the communications with the


database server
DriverManager: manages a list of database drivers.

Connection: This interface with all methods for contacting a


database
Statement: To submit the SQL statements to the database

SQLException: This class handles any errors that occur in a


database application.
JDBC packages
 The java.sql and javax.sql are the primary packages for JDBC. It offers the
main classes for interacting with your data sources.
 These packages have the following common features.
 Automatic database driver loading.

 Exception handling improvements.

 Enhanced BLOB/CLOB functionality.

 Connection and statement interface enhancements.

 National character set support.

 SQL ROWID access.

 SQL 2003 XML data type support.

 Annotations.
…..

Demonstration
remember what we discussed in the class
regarding to java database connectivity
Chapter 8
Introduction
servlet
Java servlet
 Runs on web/application server
 Act as middle layer b/n :
request(from a web browser) and
applications/database on server
For details, read the
attached pdf file

You might also like