What is JDBC?
JDBC (Java Database Database Connectivity) is a Sun Microsystems
specification. It is the Java API that is responsible for connecting to a
database, issuing queries and commands, and processing database result
sets. To access spreadsheets and databases, JDBC and database drivers
operate together. The components of JDBC that are utilized to connect to the
database are defined by the design of JDBC. The JDBC API classes and
interfaces enable an application to send a request to a specific database.
Why JDBC?
Before it was created, we utilized the ODBC API database to connect to the
database and run queries against it. The ODBC API, on the other hand, uses
the ODBC drive in C. Furthermore, it is platform-dependent and unprotected.
This is why Java created the JDBC API, which uses JDBC drivers and is
written in the Java programming language.
Applications of JDBC
JDBC enables you to create Java applications that handle the following three
programming tasks:
Make a connection to a data source, such as a database.
Send database queries and update statements.
Retrieve and process the database results that were returned in
response to your query.
Let’s discuss a real-world example that uses JDBC.
When you search for a movie on a specific date, the database retrieves the
number of tickets available on that day, and if you purchase a ticket, the
database is updated accordingly.
In addition to this domain, JDBC is used in a variety of other fields such as
banking, reservation systems, online retail websites, government portals, and
so on.
It is used in almost every Java programme that connects to an SQL database
management system. Java developers will almost probably utilize JDBC at the
lowest level, regardless of any higher-level libraries, frameworks, object-
relational mappers, or database-access layers they use.
JDBC Architecture and Components
There are two architectures of JDBC:
Two-Tier Architecture
A Java applet and application communicates directly with the data source in
the two-tier paradigm. This necessitates the use of a JDBC driver that can
interface with the data source in question. The user’s commands are
transmitted to the database or other data source, and the statements’ results
are returned to the user. The data source could be on another machine to
which the user has a network connection. A client/server configuration is one
in which the user’s machine acts as the client and the system that houses the
data source acts as the server. An intranet, for example, can connect people
within a company, or the Internet can be used as a network.
Three-Tier Architecture
Commands are sent to a “middle tier” of services in the three-tier paradigm,
which subsequently transmits the commands to the data source. The data
source interprets the commands and provides the results to the middle tier,
which ultimately passes them on to the user. The three-tier architecture
appeals to MIS directors because the intermediate tier allows them to maintain
control over access and the types of changes that can be made to company
data. Another benefit is that it makes application deployment easier. Finally,
the three-tier architecture can bring performance benefits in many
circumstances.
The components of JDBC are listed below. These elements assist us in
interacting with a database. The following are the JDBC components:
1. JDBC Driver Manager: In a JDBC application, the Driver Manager
loads database-specific drivers. This driver manager makes a database
connection. To handle the user request, it additionally makes a
database-specific call to the database.
2. Driver: A driver is an interface that manages database server
connectivity. Communication is handled using DriverManager objects.
3. JDBC-ODBC Bridge Drivers: They are used to link database drivers to
the database. The JDBC method calls are translated into ODBC method
calls by the bridge. To access the ODBC (Open Database Connectivity)
characteristics, it uses the [Link] package, which includes the
native library.
4. JDBC API: Sun Microsystem has provided JDBC API, which allows you
to write a Java program that talks with any database without modifying
the code. The JDBC API is implemented by the JDBC Driver.
5. JDBC Test Suite: The JDBC Test Suite aids in the testing of JDBC
Driver operations such as insertion, deletion, and updating. It aids in
determining whether or not the JDBC Drivers will run the program. It
ensures that the program will be run by JDBC Drivers with confidence
and conformity.
6. Database Server: This is the database server that the JDBC client
wants to communicate with, such as Oracle, MySQL, SQL Server, and
so on.
7. Statement: To send SQL statements to the database, you use objects
built using this interface. In addition to performing stored procedures,
certainly derived interfaces accept parameters.
8. RuleSet: These objects retain data retrieved from a database when you
use Statement objects to conduct a SQL query. It functions as an
iterator, allowing you to cycle through the data it contains.
9. SQL Exception: This class is responsible for any errors that occur in a
database application.
Features of JDBC 4.0
Autoloading of Driver by JVM: We used to load the driver with the
[Link]() function in previous versions. This is no longer
necessary, as the DriverManager class’s getConnection() method can
now load the proper driver.
Standard Connection Factory Management: To build the connection
before, we needed a data source URL. However, you may now supply
data source settings to the connection factory, and it will generate the
data source for you.
New interface RowID to support the ROWID data type: JDBC 4.0
included a new interface RowId for databases that support the ROWID
datatype, such as Oracle.
New Exception classes: Exception Handling classes, which are
subclasses of SQLException and handle transient and non-transient
exceptions, were added to JDBC 4.0. To iterate over-created
exceptions, SQLException added a new ‘for each’ loop functionality.
Enhanced Connection and Statement Interface: To accommodate
the new features, Jdbc 4.0 included new methods. The Connection
interface, for example, has methods to acquire and set driver-supported
client information, as well as the isValid method to check whether the
Connection state is valid. The isClosed method of the Statement
interface is used to determine whether or not the connection is closed.
These interfaces now have a slew of new methods.
XML support: To handle the XML database data type, JDBC provides
the [Link] interface. The XML type is used to store XML
values in a row as column values. It has numerous ways of getting XML
values in the form of a String, Reader or Writer, or Stream. DOM, SAX,
and other tools can parse XML data.
National Character Set Conversion Support: To handle the National
Character Set, Jdbc 4.0 includes additional data types and functions.
NCHAR, NVARCHAR, LONG VARCHAR, and NCLOB data types, as
well as methods like setNString(), getNClob(), updateNClob(), and
others, have been added.
Enhanced support for BLOBs and CLOBs: Jdbc 4.0 introduced
additional ways for dealing with huge objects such as BLOB and CLOB.
The createBlob(), createClob(), and createNClob() functions, for
example, can be used to make BLOB, CLOB, and NCLOB objects.
Advantages of JDBC Architecture
It can read any database. The only condition for it to do so is that all of
the drivers be properly installed.
It pulls information from a database and converts it to XML.
It does not necessitate the conversion of the content.
Software maintenance is centralized with no client settings necessary.
Because the driver is built in Java, the JDBC URL or a DataSource
object has all of the information required to establish a connection.
It supports queries and stored procedures completely.
The JDBC API contains a DataSource object that can be used to
identify and connect to a data source. This improves the code’s
portability and maintainability.
Both synchronous and asynchronous processing is supported.
The Java API and the JDBC API work together to make application
development simple and cost-effective.
Modules are supported.
Even if data is housed on various database management systems,
businesses can continue to use their installed databases and access
information.
Conclusion
Now that you have learned about various aspects of JDBC, you must have got
an idea of its importance. Many companies use it to develop their software
and for this, they require effective candidates who have good knowledge of
JDBC. If you want to explore more about what the questions look like in
interviews, you can refer to this link.
Java Database Connectivity
JDBC means access to the Java Database. It's a step forward for
ODBC (Open Database Connectivity). JDBC is a standard API
specification for moving data from the frontend to the backend.
This API consists of classes and interfaces written in Java.
This simply serves as an interface between your Java system and
databases (not the one we use in Java) or network, i.e. this
provides a connection between the two so that a developer can
send Java code information and store it in the database for future
use.
The Java JDBC API allows Java applications to connect to relational
databases such as MySQL, PostgreSQL, MS SQL Server, Oracle, H2
Database, etc. The JDBC API allows querying and updating
relational databases, as well as calling stored procedures, and
obtaining the database meta [Link] Java JDBC API is part of the
Java SE SDK core, making JDBC usable to all Java applications
wishing to use it. Here is a diagram of a Java program connecting
to a relational database using JDBC:
JDBC is independent from SQL
JDBC is not standardizing the SQL sent to the server. You, the
JDBC API client, are writing the SQL. The SQL dialect used by the
various databases varies slightly, so to be 100% independent of
the database, you also need to be 100% independent of the
database (i.e. use commands that are understood by all
databases).
JDBC is not for databases that are not relational
The Java JDBC API is built to communicate with relational
databases, meaning that you use standard SQL to connect with
databases. The JDBC API is not intended for non-related servers
like Mongo DB, Cassandra, Dynamo and so on. From a Java
application you can use such databases, but you should see what
drivers such databases provide for Java itself.
JDBC is independent of the type of database
The Java JDBC API standardizes how to connect to a database,
how to execute queries against it, how to access a request
output, how to execute database changes, how to call stored
procedures, and how to get meta data from the server. Through
"standardizing," I mean the repository's software looks the same
across various [Link], if your project needs this in the
future, it will be much easier to switch to another database.
Steps for Java program and database
connectivity mentioned below:
Load JDBC driver
First of all, you need to load or register the driver before you use
it in the program. You must register once in your program. In one
of the two ways listed below, you can register a driver:
[Link]()
Here at runtime we load the class file of the driver into memory.
No need to use fresh or create object. The instance below uses
[Link]() to load the Oracle driver.–
[Link]("[Link]");
[Link]():
DriverManager is an integrated Java class with a register of static
members. Here we call the driver class constructor at the moment
of compilation. [Link]() is used in the
following example/instance to register the Oracle driver -
[Link](new
[Link]())
Connectionsestablisment
We used code below after loading the driver to create
connections:
Connection connection =
[Link](DBurl,username,password)
username : it is a username from which your sql command
prompt can be accessed.
password : It is a password from which your sql command
prompt can be accessed.
connection : It is an element of connection, i.e. it is a
communication interface reference.
DBurl : It is a Uniform Resource Locator. It can be created as
follows:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where Oracle is the database used, the driver used is tiny, where
the database is located, @localhost is the IP address, 1521 is the
port number, and xe is the service provider. The 3 parameters
above are String sort, which the programmer must declare before
calling the function. You may refer to the use of this from the final
code.
Statement creation
Whether the server needs to be modified or queried, you will
need to build a JDBC Statement or JDBC PreparedStatement
through which the update or request will occur.
Statement statement = [Link]();
Query execution
Here comes the most important part, i.e. the query execution.
Here's a query from the SQL. We here understand that we can
have various kinds of questions. Some of them are the following:
Request to delete / modify / insert a table in a
database.
Request to collect or retrieve information from the
database.
The Statement interface's executeQuery) (method is used to
perform queries to extract server values. This method returns the
ResultSet item which can be used to obtain from the table all data
/ records.
The Statement interface executeUpdate(sql query) method is
used to perform update / insert.
Example:
int result = [Link](sql);
if (result == 1)
[Link]("inserted successfully : "+sql);
else
[Link]("insertion failed");
Here sql is sql query of the type String
Close database connections
You have to open the connection again when you're finished with
the JDBC server connection. In the request, but also within the
database server, a JDBC connection could take up a large amount
of sources. Therefore, after use it is important to close the
connection to the database again. You close a JDBC relation
through the method of closing). Here is an example of closing a
JDBC connection:
[Link]();
Working example below :
[Link].*;
[Link].*;
Java JDBC program below:
class MyFirstJDBCProgram
public static void main(String a[])
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String username = "India";
String password = "India";
Scanner k = new Scanner([Link]);
[Link]("enter class student name");
String Studentname = [Link]();
[Link]("enter class student roll no");
int studentRollNumber = [Link]();
[Link]("enter student current class");
String Studentcls = [Link]();
String sql = "insert into student1
values('"+Studentname+"',"+studentRollNumber+",'"+Studentcls+"
')";
Connection conn=null;
try
[Link](new [Link]());
con = [Link](url,user,pass);
Statement stmt = [Link]();
int count = [Link](sql);
if (count == 1)
[Link]("inserted student record successfully into
database : "+sql);
else
[Link]("insertion failed.");
catch(Exception ex)
[Link](ex);
} finally {
[Link]();
}
}
Java RMI
RMI (Remote method invocation)
The RMI is an API that offers a mechanism for creating distributed
implementation in Java. The RMI enables techniques/method to be
invoked by an object operating in another JVM.
The RMI uses two items, stub and skeleton, to provide distant
communication between the apps.
RMI Explanation:
The communication between client and server is treated using
two intermediate items/objects, Stub object (on the client side)
and Skeleton object (on the server side).
Stub
The stub is an object, acting on the client side as a gateway. It
routes all the outgoing applications. It lies on the side of the client
and represents the object remote. When calling technique on the
stub item, the caller performs the following duties:
It initiates a remote virtual machine (JVM) link/connection.
The parameters are written and transmitted (marshals) to
the remote Virtual Machine (JVM) by it.
It is waiting for the outcome/result.
It reads the return value or exception (unmarshals) and
At the end, it returns the value/response to the caller.
Skeleton
The skeleton is an object that acts as a gateway to the side object
of the server. It routes all incoming requests through it. When the
incoming request is received by the skeleton, the following tasks
are performed:
It reads the remote method parameter
It executes/invokes the method on the actual remote object.
It writes and transmits the result to the caller (marshals).
Below is the 6 - six steps to write the RMI program in
java.
Creation of remote interface
Provide the implementation of the remote interface
Compile the implementation class and create the stub and
skeleton objects using the rmic tool
Start the registry service by rmi registry tool
Write and start the remote application
Write and start the client application
1. First Define the java remote interface
First thing to do is create an interface to describe the techniques
that can be invoked by distant clients. This interface should
extend the Remote interface and throw the RemoteException
inside the interface using the method prototype.
// Creating a Search interface
import [Link].*;
public interface MySearch extends Remote
// Declaring the method prototype
public String query(String search) throws RemoteException;
2. Implement the java remote interface
The next step is to implement the remote interface. To execute
the remote interface, the class should extend to the
UnicastRemoteObject class [Link] package. In addition, a
default constructor must be formed to transfer the
[Link] from its class parent constructor.
// Java program to implement the MySearch interface
import [Link].*;
import [Link].*;
public class SearchQuery extends UnicastRemoteObject
implements MySearch
SearchQuery() throws RemoteException
super();
// Implementation of the query interface
public String query(String search)
throws RemoteException
String result;
if ([Link]("Reflection in Java"))
result = "Yes it’s found";
else
result = "No its not found";
return result;
3. Writing Stub and Skeleton objects from the
implementation class using rmic
The rmic instrument is used to invoke the rmi compiler which
produces the Stub and Skeleton items. His prototype is the rmic
class's name. For the above program, the following command
must be executed at the rmicSearchQuery command prompt.
4. Start/Invoke the rmiregistry
Start the service of the registry by putting the following command
on the prompt of start rmiregistry.
5. Write and execute the server application program
The next step is the development and execution on a separate
command prompt of the server application program.
The server program uses the creation technique of the
LocateRegistry class to produce rmiregistry with the passed
port number as the argument within the JVM server.
The Naming class rebind method is used to bind the remote
object to the new name.
//Java server application
import [Link].*;
import [Link].*;
public class SearchServer
public static void main(String args[])
try
// Create an object of the interface
// implementation class
Search obj = new SearchQuery();
// rmiregistry within the server JVM with
// port number 1900
[Link](1900);
// Binds the remote object by the name
[Link]("rmi://localhost:1900"+
"/test",obj);
catch(Exception ae)
{
[Link](ae);
6. Write and execute the client application program
The last stage is to generate and implement the client application
program on a distinct command prompt. The Naming class lookup
method is used to get the Stub object reference.
//Java client application
import [Link].*;
public class ClientRequest
public static void main(String args[])
String answer,value="Reflection in Java";
try
// lookup method to find reference of remote object
Search access =
(Search)[Link]("rmi://localhost:1900"+
"/test");
answer = [Link](value);
[Link]("Article on " + value +
" " + answer+" at online");
catch(Exception ae)
[Link](ae);
To use localhost, the above client and server program runs on the
same machine. To access the remote object from another device,
the localhost must be replaced with the IP address where the
remote object is present.
Points to remember:
RMI stands for invocation of the remote method. It is a
mechanism that enables the access / invoke of an
item/object operating on another JVM by an object residing
in one system (JVM).
It is used to construct/build distributed applications ; it offers
Java programs with remote communication.
The Stub and Skeleton objects are used for client-to-server
interaction.
Java Documentation
There are three kinds of comments in the Java language −
Sr.N
Comment & Description
o.
/* My Java block co
1.
The java compiler ignores everything from /* to */.
//My Java single line c
Single line comment starts with two forward slashes with no white spaces (//) and lasts till the en
2. the comment exceeds one line, then put two more consecutive slashes on the next line an
the comment.
The Java compiler ignores everything from // to the end of the line.
/** My Java documentation co
3.
This is a java documentation comment and is generally called doc comment. When
automatically produced documentation, the JDK javadoc tool utilizes doc comments.
Javadoc is a tool that comes with JDK and is used to generate Java
code documentation from Java source code in HTML format, which
needs predefined format documentation.
Following is a straightforward instance/example where Java multi-
line comments are the lines inside /* .... */. Similarly, Java's single-
line comment is the line that precedes //.
Example:
/*
* The MyHelloWorldProgramprogram is a program
* that simply displays "My name is John!" to the standard
* output.
*/
public class MyHelloWorldProgram {
public static void main(String[] args){
// Prints My name is John! on standard output.
[Link]("My name is John!");
Inside the description section, you can include necessary HTML
tags. For example, < h1> .... </h1 > for heading is used in the
following example and < p > is used to create paragraph break
−
Example:
/**
* <h 1> Hello, World! </h 1>
* The MyHelloWorldProgramprogram implements an application
* that simply displays "My name is John!" to the output.
* <p>
* Giving proper comments in your program makes it more
* user friendly and it is assumed as a high quality code.
* </p>
*/
public class MyHelloWorldProgram {
public static void main(String[] args){
/* Prints My name is John!"! on standard output.
[Link]("My name is John!");
The javadoc tool acknowledges the tags below −
Tag Description Syntax
@author Adds the author of a class. @author name-text
Displays text in code font without interpreting the text
{@code} {@code text}
as HTML markup or nested javadoc tags.
Represents the relative path to the generated
{@docRoot} {@docRoot}
document's root directory from any generated page.
Adds a comment indicating that this API should no
@deprecated @deprecated depre
longer be used.
Tag Description Syntax
Adds a Throws subheading to the generated
@exception
@exception documentation, with the classname and description
description
text.
Inherits a comment from the nearest inheritable class Inherits a commen
{@inheritDoc}
or implementable interface. immediate surpercl
Inserts an in-line link with the visible text label that {@link
{@link} points to the documentation for the specified package, [Link]#mem
class, or member name of a referenced class. label}
{@linkplain
Identical to {@link}, except the link's label is displayed
{@linkplain} [Link]#mem
in plain text than code font.
label}
Adds a parameter with the specified parameter-name
@param param
@param followed by the specified description to the
description
"Parameters" section.
@return Adds a "Returns" section with the description text. @return description
Adds a "See Also" heading with a link or text entry that
@see @see reference
points to reference.
Tag Description Syntax
Used in the doc comment for a default serializable @serial field-des
@serial
field. include | exclude
Documents the data written by the writeObject( ) or
@serialData @serialData data-d
writeExternal( ) methods.
@serialField field-n
@serialField Documents an ObjectStreamField component.
type field-descriptio
Adds a "Since" heading with the specified since-text to
@since @since release
the generated documentation.
@throws
@throws The @throws and @exception tags are synonyms.
description
When {@value} is used in the doc comment of a static
{@value} {@value package.c
field, it displays the value of that constant.
Adds a "Version" subheading with the specified
@version version-text to the generated docs when the -version @version version-te
option is used.
Example:
The program that follows utilizes a few of the significant tags
accessible to comments for the documentation. Based on your
demands, you can use other tags also.
The MultiplyNum class documentation will be produced in the
[Link] i.e. a HTML file, but at the same time a master
file with an [Link] name will also be created.
import [Link].*;
/**
* <h 1>Multiply 2 Numbers!</h 1>
* The MultiplyNumprogram implements an application that
* simply multiply two given integer numbers and Prints
* the output on the screen.
* <p>
* <b>Note:</b> Giving proper comments in your program makes it
more
* user friendly and it is assumed as a high quality code.
* @author John Walter
* @version 2.0
* @since 2019-03-16
*/
public class MultiplyNum{
/**
* This method is used to multiply two integers. This is
* a the simplest form of a class method, just to
* show the usage of various javadoc Tags.
* @param numA This is the first paramter to multiplyNum
* method
* @param numB This is the second parameter to multiplyNum
method
* @return int This returns multiplication of numA and
numB.
*/
public int multiplyNum (int numA,int numB){
return numA * numB;
/**
* This is the main method which makes use of addNum
method.
* @param args Unused.
* @return Nothing.
* @exception IOException On input error.
* @see IOException
*/
public static void main(String args[])throws IOException{
MultiplyNum obj =new MultiplyNum();
int result = obj. multiplyNum(10,20);
[Link]("Multiplication of 10 and 20 is :"+
result);
Now, process the above [Link] file using javadoc utility
as follows –
$ javadoc [Link]
Java Virtual Machine
JVM in java
JVM is an engine that offers the Java Code or applications runtime
environment. It transforms bytecode Java into the language of
computers. JVM (Java Run Environment) is a component of JRE. It
is a Java Virtual Machine.
The compiler generates machine code for a specific scheme
in other programming languages. However, for a virtual
machine known as Java Virtual Machine, Java compiler
generates code.
First, the bytecode for Java code is generated. This bytecode
is interpreted on various computers
Bytecode is an intermediate code between the host system
and the source code of Java.
JVM is accountable for memory space allocation.
JVM is an abstract machine (Java Virtual Machine). It is a
specification that offers runtime environment and allows the
execution of java bytecode.
For many hardware and software platforms, JVMs are available
(i.e. JVM depends on the platform).
JVM is the Java Virtual Machine – it actually executes Java
ByteCode.
JRE is the Java Runtime Environment – it contains a JVM, among
other things, and is what you need to run a Java program.
JDK is the Java Development Kit – it is the JRE, but with javac
(which is what you need to compile Java source code) and has
other programming tools added.
Let's comprehend JVM's inner architecture. It includes classloader,
region of memory, engine of execution, etc.
Classloader is a JVM subsystem for loading class files. Every time
we run the java program, the classloader loads it first. In Java,
there are three integrated class loaders.
Bootstrap ClassLoader: This is the first-class loader to the
Extension class loader super class. It loads the [Link] file
containing all Java Standard Edition class files such as
package classes [Link], package classes [Link],
package classes [Link], package classes [Link], package
classes [Link] etc.
Extension ClassLoader: This is Bootstrap's child
classloader and System classloader's parent classloader. It
loads the jar documents within the folder of $JAVA HOME /
jre / lib / ext.
System/Application ClassLoader: It 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.
// Below is an example to print the classloadername in java
publicclass MyClassLoaderProgram
publicstaticvoid main(String[] args)
Class c= [Link];
[Link]([Link]());
[Link]([Link]());
These are Java's inner class loaders. You need to extend the
ClassLoader class if you want to create your own classloader.
Class (Method) Area
Class(Method) Area stores structures per class such as the
runtime constant pool, field and method data, the method code.
Heap
It is the runtime data pool in which objects are placed.
Stack
Frames are stored in Java Stack. It maintains local variables and
partial outcomes and plays a role in invoking and returning the
method.
Each thread has a personal JVM stack, which is generated
simultaneously with a thread.
Every time a method is invoked, a new frame is developed. When
the invocation method finishes, a frame is demolished.
Program Counter Register
PC (program counter) register includes the address of the
presently executed Java virtual machine instruction.
Native Method Stack
It includes all of the application's native methods.
Execution Engine
It contains the below things:
A virtual processor
Interpreter: Execute the instruction by reading the
bytecode stream.
Just-In-Time (JIT) compiler: Used for performance
enhancement. JIT compiles parts of the byte code that
simultaneously have similar functionality, thus reducing the
amount of time required for compilation. The word
"compiler" here relates to a translator from a Java virtual
machine's instruction set (JVM) to a particular CPU's
instruction set.
Java Native Interface
Java Native Interface (JNI) is a framework for communicating with
another application written in a different language such as C, C+
+, Assembly, etc. Java utilizes JNI framework to send output or
communicate with OS libraries to the Console
Introduction to JDBC (Java Database
Connectivity)
Last Updated : 10 Jun, 2024
JDBC stands for Java Database Connectivity. JDBC is a Java
API to connect and execute the query with the database. It is a
specification from Sun Microsystems that provides a standard
abstraction(API or Protocol) for Java applications to communicate
with various databases. It provides the language with Java
database connectivity standards. It is used to write programs
required to access databases. JDBC, along with the database
driver, can access databases and spreadsheets. The enterprise
data stored in a relational database(RDB) can be accessed with
the help of JDBC APIs.
Definition of JDBC(Java Database
Connectivity)
JDBC is an API(Application programming interface) used in Java
programming to interact with databases.
The classes and interfaces of JDBC allow the
application to send requests made by users to the specified
database. The current version of JDBC is JDBC 4.3, released on
21st September 2017.
Purpose of JDBC
Enterprise applications created using the JAVA EE technology
need to interact with databases to store application-specific
information. So, interacting with a database requires efficient
database connectivity, which can be achieved by using
the ODBC(Open database connectivity) driver. This driver is used
with JDBC to interact or communicate with various kinds of
databases such as Oracle, MS Access, Mysql, and SQL server
database.
Components of JDBC
There are generally four main components of JDBC through which
it can interact with a 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 Java EE platforms to exhibit
WORA(write once run anywhere) capabilities.
The [Link] package contains interfaces and classes of JDBC API.
[Link]: This package provides APIs for data access and data
process in a relational database, included in
Java Standard Edition (java SE)
[Link]: This package extends the functionality of java
package by providing datasource interface for
establishing connection pooling, statement
pooling with a data source, included in
Java Enterprise Edition (java EE)
It also provides a standard to connect a database to a client
application.
2. JDBC Driver manager: It loads a database-specific driver in
an application to establish a connection with a database. It is
used to make a database-specific call to the database to process
the user request.
3. JDBC Test suite: It is used to test the operation(such as
insertion, deletion, updation) being performed by JDBC Drivers.
4. JDBC-ODBC Bridge Drivers: It connects database drivers to
the database. This bridge translates the JDBC method call to the
ODBC function call. It makes use of the [Link] package
which includes a native library to access ODBC characteristics.
Architecture of JDBC
Description:
1. Application: It is a java applet or a servlet that
communicates with a data source.
1. The JDBC API: The JDBC API allows Java programs to
execute SQL statements and retrieve results. Some of the
important interfaces defined in JDBC API are as follows: Driver
interface , ResultSet Interface , RowSet Interface ,
PreparedStatement interface, Connection inteface, and
cClasses defined in JDBC API are as follows: DriverManager
class, Types class, Blob class, clob class.
1. DriverManager: It plays an important role in the JDBC
architecture. It uses some database-specific drivers to
effectively connect enterprise applications to databases.
1. JDBC drivers: To communicate with a data source through
JDBC, you need a JDBC driver that intelligently communicates
with the respective data source.
Types of JDBC Architecture(2-tier and 3-tier)
The JDBC architecture consists of two-tier and three-tier
processing models to access a database. They are as described
below:
1. Two-tier model: A java application communicates directly
to the data source. The JDBC driver enables the communication
between the application and the data source. When a user
sends a query to the data source, the answers for those
queries are sent back to the user in the form of results.
The data source can be located on a different machine on a
network to which a user is connected. This is known as
a client/server configuration, where the user’s machine acts
as a client, and the machine has the data source running acts
as the server.
1. Three-tier model: In this, the user’s queries are sent to
middle-tier services, from which the commands are again sent
to the data source. The results are sent back to the middle tier,
and from there to the user.
This type of model is found very useful by management
information system directors.
What is API?
Before jumping into JDBC Drivers, let us know more about API.
API stands for Application Programming Interface. It is
essentially a set of rules and protocols which transfers data
between different software applications and allow different
software applications to communicate with each other. Through
an API one application can request information or perform a
function from another application without having direct access to
it’s underlying code or the application data.
JDBC API uses JDBC Drivers to connect with the database.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client
machine, not on the server) that convert requests from Java
programs to a protocol that the DBMS can understand. There are
4 types of JDBC drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
1. Type-2 driver or Native-API driver (partially java driver)
1. Type-3 driver or Network Protocol driver (fully java driver)
1. Type-4 driver or Thin driver (fully java driver)
Interfaces of JDBC API
A list of popular interfaces of JDBC API is given below:
Driver interface
Connection interface
Statement interface
PreparedStatement interface
CallableStatement interface
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
RowSet interface
Classes of JDBC API
A list of popular classes of JDBC API is given below:
DriverManager class
Blob class
Clob class
Types class
Working of JDBC
Java application that needs to communicate with the database
has to be programmed using JDBC API. JDBC Driver supporting
data sources such as Oracle and SQL server has to be added in
java application for JDBC support which can be done dynamically
at run time. This JDBC driver intelligently communicates the
respective data source.
Creating a simple JDBC application:
Java
1
//Java program to implement a simple JDBC application
2
package [Link];
3
4
import [Link].*;
5
6
public class JDBCDemo {
7
8
public static void main(String args[])
9
throws SQLException, ClassNotFoundException
10
{
11
String driverClassName
12
= "[Link]";
13
String url = "jdbc:odbc:XE";
14
String username = "scott";
15
String password = "tiger";
16
String query
17
= "insert into students values(109, 'bhatt')";
18
19
// Load driver class
20
[Link](driverClassName);
21
22
// Obtain a connection
23
Connection con = [Link](
24
url, username, password);
25
26
// Obtain a statement
27
Statement st = [Link]();
28
29
// Execute the query
30
int count = [Link](query);
31
[Link](
32
"number of rows affected by this query= "
33
+ count);
34
35
// Closing the connection as per the
36
// requirement with connection is completed
37
[Link]();
38
}
39
} // class
The above example demonstrates the basic steps to access a
database using JDBC. The application uses the JDBC-ODBC bridge
driver to connect to the database. You must
import [Link] package to provide basic SQL functionality and
use the classes of the package.
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.
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
Comment
More info
Next Article
JDBC Drivers
Similar Reads
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having
connectivity with any one of jars of RDBMS like MySQL, Oracle, or
SQL Server, etc., For example, if we are connecting with MySQL,
then we need to connect "mysql-connector-java". Let us see how
a [Link] file of a maven project looks like. C/C++ Code <?xml
version="1.0" encoding=
4 min read
Java Database Connectivity with MySQL
In Java, we can connect our Java application with the MySQL
database through the Java code. JDBC ( Java Database
Connectivity) is one of the standard APIs for database
connectivity, using it we can easily run our query, statement, and
also fetch data from the database. Prerequisite to understand
Java Database Connectivity with MySQL 1. You should h
3 min read
How to Execute Multiple SQL Commands on a
Database Simultaneously in JDBC?
Java Database Connectivity also is known as JDBC is an
application programming interface in Java that is used to establish
connectivity between a Java application and database. JDBC
commands can be used to perform SQL operations from the Java
application. Demonstrating execution of multiple SQL commands
on a database simultaneously using the addBat
6 min read
Checking Internet Connectivity using Java
Checking Internet connectivity using Java can be done using 2
methods: 1) by using getRuntime() method of java Runtime class.
2) by using methods of java URL and URLConnection classes.
#Java Runtime Class:This class is used to interact with java
runtime environment (Java virtual machine) in which the
application is running. It provides methods/func
2 min read
Difference between JDBC and Hibernate in Java
Java is one of the most powerful and popular server-side
languages in the current scenario. One of the main features of a
server-side language is the ability to communicate with the
databases. In this article, let's understand the difference between
two ways of connecting to the database (i.e.) JDBC and Hibernate.
Before getting into the difference
2 min read
Java Program to Retrieve Contents of a Table Using
JDBC connection
It can be of two types namely structural and non-structural
database. The structural database is the one which can be stored
in row and columns. A nonstructural database can not be stored
in form of rows and columns for which new concepts are
introduced which would not be discussing here. Most of the real-
world data is non-structural like photos, v
5 min read
Java JDBC - Difference Between Row Set and Result
Set
ResultSet characteristics are as follows: It maintains a connection
to a database and because of that, it can’t be [Link] can not
pass the Result set object from one class to another class across
the [Link] object maintains a cursor pointing to its
current row of data. Initially, the cursor is positioned before the
first row. The
2 min read
Difference Between Connected vs Disconnected
RowSet in Java JDBC
A RowSet is a wrapper around a ResultSet object. It can be
connected, disconnected from the database, and can be
serialized. It maintains a JavaBean component by setting the
properties. You can pass a RowSet object over the network. By
default, the RowSet object is scrollable and updatable. This
diagram will give you more idea about ResultSet and R
5 min read
Working with Large Objects Using JDBC in Java
Sometimes as part of programming requirements, we have to
insert and retrieve large files like images, video files, audio files,
resumes, etc with respect to the database. Example: Uploading
images on the matrimonial websiteUpload resume on job-related
websites To store and retrieve large information we should go for
Large Objects(LOBs). There are
5 min read
Establishing JDBC Connection in Java
Before Establishing JDBC Connection in Java (the front end i.e your
Java Program and the back end i.e 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. What is JDBC? JDBC is
an acronym for
6 min read
What is RowSet in Java JDBC?
RowSet is an interface in java that is present in the [Link]
package. Geek do note not to confuse RowSet with ResultSet.
Note: RowSet is present in package [Link] while ResultSet is
present in package [Link]. The instance of RowSet is the java
bean component because it has properties and a java bean
notification mechanism. It is introduced
3 min read
How to pre populate database in Android using
SQLite Database
Introduction : Often, there is a need to initiate an Android app
with an already existing database. This is called prepopulating a
database. In this article, we will see how to pre-populate database
in Android using SQLite Database. The database used in this
example can be downloaded as Demo Database. To prepopulate a
SQLite database in an Android
7 min read
How to Commit a Query in JDBC?
COMMIT command is used to permanently save any transaction
into the database. It is used to end your current transaction and
make permanent all changes performed in the transaction. A
transaction is a sequence of SQL statements that Oracle Database
treats as a single unit. This statement also erases all save points
in the transaction and releases t
5 min read
Simplifying CRUD Operation with JDBC
Creating, reading, updating, and deleting data in a database is a
common task in many applications, and JDBC (Java Database
Connectivity) is a Java API that allows you to connect to a
database and perform these operations. In this blog post, we will
walk through the steps of setting up a simple CRUD (create, read,
update, delete) operation using JD
3 min read
How to Insert Records to a Table using JDBC
Connection?
Before inserting contents in a table we need to connect our java
application to our database. Java has its own API which JDBC API
which uses JDBC drivers for database connections. Before JDBC,
ODBC API was used but it was written in C which means it was
platform-dependent. JDBC API provides the applications-to-JDBC
connection and JDBC driver provid
4 min read
Delete Contents From Table Using JDBC
JDBC(Java Database Connectivity) is a standard API(application
interface) between the java programming language and various
databases like Oracle, SQL, PostgreSQL, etc. It connects the front
end(for interacting with the users) with the backend(for storing
data). Approach: 1. CREATE DATABASE: Create a database using
sqlyog and create some tables in
2 min read
JDBC - Type 4 Driver
Let us do get a cover overview of the JDBC and the ODBC prior in
order to better understand what exactly is type 4 driver. A JDBC
driver enables Java application to interact with a database from
where we can fetch or store data. JDBC drivers are analogous to
ODBC drivers. The JDBC classes are contained in the Java Package
[Link] and [Link]
3 min read
JDBC - Type 2 Driver
A JDBC driver enables Java application to interact with a database
from where we can fetch or store data. JDBC drivers are
analogous to ODBC drivers. The JDBC classes are contained in the
Java Package [Link] and [Link] helps to Connect to a
data source, like a [Link] queries and update statements
to the databaseRetrieve and process
2 min read
JDBC - Type 1 Driver
A JDBC driver enables Java application to interact with a database
from where we can fetch or store data. JDBC drivers are
analogous to ODBC drivers. The JDBC classes are contained in the
Java Package [Link] and [Link] helps to Connect to a
data source, like a [Link] queries and update statements
to the databaseRetrieve and process
3 min read
JDBC - Type 3 Driver
A JDBC driver enables Java application to interact with a database
from where we can fetch or store data. JDBC drivers are
analogous to ODBC drivers. The JDBC classes are contained in the
Java Package [Link] and [Link] helps to Connect to a
data source, like a [Link] queries and update statements
to the databaseRetrieve and process
2 min read
JDBC Drivers
Last Updated : 20 Nov, 2023
Java Database Connectivity (JDBC) is an application
programming interface (API) for the programming language Java,
which defines how a client may access any kind of tabular data,
especially a relational database. JDBC Drivers uses JDBC APIs
which was developed by Sun Microsystem, but now this is a part
of Oracle. There are 4 types of JDBC drivers. It is part of the Java
Standard Edition platform, from Oracle Corporation. It acts as a
middle-layer interface between Java applications and databases.
The JDBC classes are contained in the Java
Package [Link] and [Link].
JDBC helps you to write Java applications that manage these three
programming activities:
1. Connect to a data source, like a database.
1. Send queries and update statements to the database
1. Retrieve and process the results received from the database
in answer to your query
Structure of JDBC
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client
machine, not on the server) that convert requests from Java
programs to a protocol that the DBMS can understand. JDBC
drivers are the software components which implements
interfaces in JDBC APIs to enable java application to interact with
the database. Now we will learn how many JDBC driver types does
Sun defines? There are four types of JDBC drivers defined by Sun
Microsystem that are mentioned below:
1. Type-1 driver or JDBC-ODBC bridge driver
1. Type-2 driver or Native-API driver
1. Type-3 driver or Network Protocol driver
1. Type-4 driver or Thin driver
1. JDBC-ODBC bridge driver – Type 1 driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to
connect to the database. The JDBC-ODBC bridge driver converts
JDBC method calls into the ODBC function calls. Type-1 driver is
also called Universal driver because it can be used to connect to
any of the databases.
Advantages
This driver software is built-in with JDK so no need to install
separately.
It is a database independent driver.
Disadvantages
As a common driver is used in order to interact with different
databases, the data transferred through this driver is not so
secured.
The ODBC bridge driver is needed to be installed in
individual client machines.
Type-1 driver isn’t written in java, that’s why it isn’t a
portable driver.
2. Native-API driver – Type 2 driver ( Partially Java
driver)
The Native API driver uses the client -side libraries of the
database. This driver converts JDBC method calls into native calls
of the database API. In order to interact with different database,
this driver needs their local API, that’s why data transfer is much
more secure as compared to type-1 driver. This driver is not fully
written in Java that is why it is also called Partially Java driver.
Advantage
Native-API driver gives better performance than JDBC-ODBC
bridge driver.
Disadvantages
Driver needs to be installed separately in individual client
machines
The Vendor client library needs to be installed on client
machine.
Type-2 driver isn’t written in java, that’s why it isn’t a
portable driver
It is a database dependent driver.
3. Network Protocol driver – Type 3 driver (fully Java
driver)
The Network Protocol driver uses middleware (application server)
that converts JDBC calls directly or indirectly into the vendor-
specific database protocol. Here all the database connectivity
drivers are present in a single server, hence no need of individual
client-side installation.
Advantages
Type-3 drivers are fully written in Java, hence they are
portable drivers.
No client side library is required because of application
server that can perform many tasks like auditing, load
balancing, logging etc.
Switch facility to switch over from one database to another
database.
Disadvantages
Network support is required on client machine.
Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done in the
middle tier.
4. Thin driver – Type 4 driver (fully Java driver)
Type-4 driver is also called native protocol driver. This driver
interact directly with database. It does not require any native
database library, that is why it is also known as Thin Driver.
Advantages
Does not require any native library and Middleware server,
so no client-side or server-side installation.
It is fully written in Java language, hence they are portable
drivers.
Disadvantage
If the database varies, then the driver will carry because it is
database dependent.
Which Driver to use When?
If you are accessing one type of database, such as Oracle,
Sybase, or IBM, the preferred driver type is type-4.
If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred driver.
Type 2 drivers are useful in situations, where a type 3 or
type 4 driver is not available yet for your database.
The type 1 driver is not considered a deployment-level
driver, and is typically used for development and testing
purposes only.
JDBC Drivers
Last Updated : 20 Nov, 2023
Java Database Connectivity (JDBC) is an application
programming interface (API) for the programming language Java,
which defines how a client may access any kind of tabular data,
especially a relational database. JDBC Drivers uses JDBC APIs
which was developed by Sun Microsystem, but now this is a part
of Oracle. There are 4 types of JDBC drivers. It is part of the Java
Standard Edition platform, from Oracle Corporation. It acts as a
middle-layer interface between Java applications and databases.
The JDBC classes are contained in the Java
Package [Link] and [Link].
JDBC helps you to write Java applications that manage these three
programming activities:
1. Connect to a data source, like a database.
1. Send queries and update statements to the database
1. Retrieve and process the results received from the database
in answer to your query
Structure of JDBC
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client
machine, not on the server) that convert requests from Java
programs to a protocol that the DBMS can understand. JDBC
drivers are the software components which implements
interfaces in JDBC APIs to enable java application to interact with
the database. Now we will learn how many JDBC driver types does
Sun defines? There are four types of JDBC drivers defined by Sun
Microsystem that are mentioned below:
1. Type-1 driver or JDBC-ODBC bridge driver
1. Type-2 driver or Native-API driver
1. Type-3 driver or Network Protocol driver
1. Type-4 driver or Thin driver
1. JDBC-ODBC bridge driver – Type 1 driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to
connect to the database. The JDBC-ODBC bridge driver converts
JDBC method calls into the ODBC function calls. Type-1 driver is
also called Universal driver because it can be used to connect to
any of the databases.
Advantages
This driver software is built-in with JDK so no need to install
separately.
It is a database independent driver.
Disadvantages
As a common driver is used in order to interact with different
databases, the data transferred through this driver is not so
secured.
The ODBC bridge driver is needed to be installed in
individual client machines.
Type-1 driver isn’t written in java, that’s why it isn’t a
portable driver.
2. Native-API driver – Type 2 driver ( Partially Java
driver)
The Native API driver uses the client -side libraries of the
database. This driver converts JDBC method calls into native calls
of the database API. In order to interact with different database,
this driver needs their local API, that’s why data transfer is much
more secure as compared to type-1 driver. This driver is not fully
written in Java that is why it is also called Partially Java driver.
Advantage
Native-API driver gives better performance than JDBC-ODBC
bridge driver.
Disadvantages
Driver needs to be installed separately in individual client
machines
The Vendor client library needs to be installed on client
machine.
Type-2 driver isn’t written in java, that’s why it isn’t a
portable driver
It is a database dependent driver.
3. Network Protocol driver – Type 3 driver (fully Java
driver)
The Network Protocol driver uses middleware (application server)
that converts JDBC calls directly or indirectly into the vendor-
specific database protocol. Here all the database connectivity
drivers are present in a single server, hence no need of individual
client-side installation.
Advantages
Type-3 drivers are fully written in Java, hence they are
portable drivers.
No client side library is required because of application
server that can perform many tasks like auditing, load
balancing, logging etc.
Switch facility to switch over from one database to another
database.
Disadvantages
Network support is required on client machine.
Maintenance of Network Protocol driver becomes costly
because it requires database-specific coding to be done in the
middle tier.
4. Thin driver – Type 4 driver (fully Java driver)
Type-4 driver is also called native protocol driver. This driver
interact directly with database. It does not require any native
database library, that is why it is also known as Thin Driver.
Advantages
Does not require any native library and Middleware server,
so no client-side or server-side installation.
It is fully written in Java language, hence they are portable
drivers.
Disadvantage
If the database varies, then the driver will carry because it is
database dependent.
Which Driver to use When?
If you are accessing one type of database, such as Oracle,
Sybase, or IBM, the preferred driver type is type-4.
If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred driver.
Type 2 drivers are useful in situations, where a type 3 or
type 4 driver is not available yet for your database.
The type 1 driver is not considered a deployment-level
driver, and is typically used for development and testing
purposes only.
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
Establishing JDBC Connection in Java
Last Updated : 17 Nov, 2023
Before Establishing JDBC Connection in Java (the front end i.e
your Java Program and the back end i.e 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.
What is JDBC?
JDBC is an acronym for Java Database Connectivity. It’s an
advancement for ODBC ( Open Database Connectivity ). JDBC is a
standard API specification developed in order to move data from
the front end to the back end. This API consists of classes and
interfaces written in Java. It basically acts as an interface (not the
one we use in Java) or channel between your Java program and
databases i.e it establishes a link between the two so that a
programmer can send data from Java code and store it in the
database for future use.
Illustration: Working of JDBC co-relating with real-time
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:
Step 1– Import the Packages
Step 2 – Load the drivers using the forName() method
Step 3– Register the drivers using DriverManager
Step 4 – Establish a connection using the Connection class object
Step 5– Create a statement
Step 6– Execute the query
Step 7 – Close the connections
Java Database Connectivity
Let us discuss these steps in brief before implementing by writing
suitable code to illustrate connectivity steps for JDBC.
Step 1: Import the Packages
Step 2: Loading the drivers
In order to begin with, you first need to load the driver or register
it before using it in the program. Registration is to be done once
in your program. You can register a driver in one of two ways
mentioned below as follows:
2-A [Link]()
Here we load the driver’s class file into memory at the runtime.
No need of using new or create objects. The following example
uses [Link]() to load the Oracle driver as shown below as
follows:
[Link](“[Link]”);
2-B [Link]()
DriverManager is a Java inbuilt class with a static member
register. Here we call the constructor of the driver class at
compile time. The following example uses
[Link]()to register the Oracle driver as
shown below:
[Link](new
[Link]())
Step 3: Establish a connection using the Connection
class object
After loading the driver, establish connections as shown below as
follows:
Connection con =
[Link](url,user,password)
user: Username from which your SQL command prompt can
be accessed.
password: password from which the SQL command prompt
can be accessed.
con: It is a reference to the Connection interface.
Url: Uniform Resource Locator which is created as shown
below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used,
@localhost is the IP Address where a database is stored, 1521 is
the port number and xe is the service provider. All 3 parameters
above are of String type and are to be declared by the
programmer before calling the function. Use of this can be
referred to form the final code.
Step 4: Create a statement
Once a connection is established you can interact with the
database. The JDBCStatement, CallableStatement, and
PreparedStatement interfaces define the methods that enable you
to send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = [Link]();
Note: Here, con is a reference to Connection interface used in
previous step .
Step 5: Execute the query
Now comes the most important part i.e executing the query. The
query here is an SQL Query. Now we know we can have multiple
types of queries. Some of them are as follows:
The query for updating/inserting a table in a database.
The query for retrieving data.
The executeQuery() method of the Statement interface is used
to execute queries of retrieving values from the database. This
method returns the object of ResultSet that can be used to get all
the records of a table.
The executeUpdate(sql query) method of the Statement interface
is used to execute queries of updating/inserting.
Pseudo Code:
int m = [Link](sql);
if (m==1)
[Link]("inserted successfully : "+sql);
else
[Link]("insertion failed");
Here sql is SQL query of the type String:
Java
// This code is for establishing connection with MySQL
// database and retrieving data
// from db Java Database connectivity
/*
*1. import --->[Link]
*2. load and register the driver ---> [Link].
*3. create connection
*4. create a statement
*5. execute the query
*6. process the results
*7. close
*/
import [Link].*;
import [Link].*;
class GFG {
public static void main(String[] args) throws Exception
String url
= "jdbc:mysql://localhost:3306/table_name"; // table details
String username = "rootgfg"; // MySQL credentials
String password = "gfg123";
String query
= "select *from students"; // query to be run
[Link](
"[Link]"); // Driver name
Connection con = [Link](
url, username, password);
[Link](
"Connection Established successfully");
Statement st = [Link]();
ResultSet rs
= [Link](query); // Execute query
[Link]();
String name
= [Link]("name"); // Retrieve name from db
[Link](name); // Print result on console
[Link](); // close statement
[Link](); // close connection
[Link]("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 close the connection. It is shown below as follows:
[Link]();
Example:
Java
// Java Program to Establish Connection in JDBC
// Importing database
import [Link].*;
// Importing required classes
import [Link].*;
// Main class
class Main {
// Main driver method
public static void main(String a[])
// Creating the connection using Oracle DB
// Note: url syntax is standard, so do grasp
String url = "jdbc:oracle:thin:@localhost:1521:xe";
// Username and password to access DB
// Custom initialization
String user = "system";
String pass = "12345";
// Entering the data
Scanner k = new Scanner([Link]);
[Link]("enter name");
String name = [Link]();
[Link]("enter roll no");
int roll = [Link]();
[Link]("enter class");
String cls = [Link]();
// Inserting data using SQL query
String sql = "insert into student1 values('" + name
+ "'," + roll + ",'" + cls + "')";
// Connection class object
Connection con = null;
// Try block to check for exceptions
try {
// Registering drivers
[Link](
new [Link]());
// Reference to connection interface
con = [Link](url, user,
pass);
// Creating a statement
Statement st = [Link]();
// Executing query
int m = [Link](sql);
if (m == 1)
[Link](
"inserted successfully : " + sql);
else
[Link]("insertion failed");
// Closing the connections
[Link]();
// Catch block to handle exceptions
catch (Exception ex) {
// Display message when exceptions occurs
[Link](ex);
Output after importing data in the database:
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
Types of Statements in JDBC
Last Updated : 07 Aug, 2024
The Statement interface in JDBC is used to create SQL statements
in Java and execute queries with the database. There are different
types of statements used in JDBC:
Create Statement
Prepared Statement
Callable Statement
1. Create a Statement:
A Statement object is used for general-purpose access to databases
and is useful for executing static SQL statements at runtime.
Syntax:
Statement statement = [Link]();
Implementation: Once the Statement object is created, there
are three ways to execute it.
boolean execute(String SQL): If the ResultSet object is
retrieved, then it returns true else false is returned. Is used to
execute SQL DDL statements or for dynamic SQL.
int executeUpdate(String SQL): Returns number of rows
that are affected by the execution of the statement, used when
you need a number for INSERT, DELETE or UPDATE statements.
ResultSet executeQuery(String SQL): Returns a
ResultSet object. Used similarly as SELECT is used in SQL.
Example:
Java
// Java Program illustrating Create Statement in JDBC
2
// Importing Database(SQL) classes
4
import [Link].*;
5
// Class
7
class GFG {
8
// Main driver method
10
public static void main(String[] args)
11
{
12
13
// Try block to check if any exceptions occur
14
try {
15
16
// Step 2: Loading and registering drivers
17
18
// Loading driver using forName() method
19
[Link]("[Link]");
20
21
// Registering driver using DriverManager
22
Connection con = [Link](
23
"jdbc:mysql:///world", "root", "12345");
24
25
// Step 3: Create a statement
26
Statement statement = [Link]();
27
String sql = "select * from people";
28
29
// Step 4: Execute the query
30
ResultSet result = [Link](sql);
31
32
// Step 5: Process the results
33
34
// Condition check using hasNext() method which
35
// holds true till there is single element
36
// remaining in List
37
while ([Link]()) {
38
39
// Print name an age
40
[Link](
41
"Name: " + [Link]("name"));
42
[Link](
43
"Age:" + [Link]("age"));
44
}
45
}
46
47
// Catching database exceptions if any
48
catch (SQLException e) {
49
50
// Print the exception
51
[Link](e);
52
}
53
54
// Catching generic ClassNotFoundException if any
55
catch (ClassNotFoundException e) {
56
57
// Print and display the line number
58
// where exception occurred
59
[Link]();
60
}
61
}
62
}
Output:
Name and age are as shown for random inputs.
2. Prepared Statement:
A PreparedStatement represents a precompiled SQL statement that
can be executed multiple times. It accepts parameterized SQL
queries, with ? as placeholders for parameters, which can be set
dynamically.
Illustration:
Considering in the people database if there is a need to INSERT
some values, SQL statements such as these are used:
INSERT INTO people VALUES ("Ayan",25);
INSERT INTO people VALUES("Kriya",32);
To do the same in Java, one may use Prepared Statements and
set the values in the ? holders, setXXX() of a prepared statement
is used as shown:
String query = "INSERT INTO people(name, age)VALUES(?, ?)";
PreparedStatement pstmt = [Link](query);
[Link](1,"Ayan");
[Link](2,25);
// where pstmt is an object name
Implementation: Once the PreparedStatement object is created,
there are three ways to execute it:
execute(): This returns a boolean value and executes a
static SQL statement that is present in the prepared statement
object.
executeQuery(): Returns a ResultSet from the current
prepared statement.
executeUpdate(): Returns the number of rows affected by
the DML statements such as INSERT, DELETE, and more that is
present in the current Prepared Statement.
Example:
Java
// Java Program illustrating Prepared Statement in JDBC
2
// Step 1: Importing DB(SQL here) classes
4
import [Link].*;
5
// Importing Scanner class to
6
// take input from the user
7
import [Link];
8
// Main class
10
class GFG {
11
12
// Main driver method
13
public static void main(String[] args)
14
{
15
// try block to check for exceptions
16
try {
17
18
// Step 2: Establish a connection
19
20
// Step 3: Load and register drivers
21
22
// Loading drivers using forName() method
23
[Link]("[Link]");
24
25
// Scanner class to take input from user
26
Scanner sc = new Scanner([Link]);
27
28
// Display message for ease for user
29
[Link](
30
"What age do you want to search?? ");
31
32
// Reading age an primitive datatype from user
33
// using nextInt() method
34
int age = [Link]();
35
36
// Registering drivers using DriverManager
37
Connection con = [Link](
38
"jdbc:mysql:///world", "root", "12345");
39
40
// Step 4: Create a statement
41
PreparedStatement ps = [Link](
42
"select name from [Link] where age = ?");
43
44
// Step 5: Execute the query
45
[Link](1, age);
46
ResultSet result = [Link]();
47
48
// Step 6: Process the results
49
50
// Condition check using next() method
51
// to check for element
52
while ([Link]()) {
53
54
// Print and display elements(Names)
55
[Link]("Name : "
56
+ [Link](1));
57
}
58
59
// Step 7: Closing the connections
60
// (Optional but it is recommended to do so)
61
}
62
63
// Catch block to handle database exceptions
64
catch (SQLException e) {
65
66
// Display the DB exception if any
67
[Link](e);
68
}
69
70
// Catch block to handle class exceptions
71
catch (ClassNotFoundException e) {
72
73
// Print the line number where exception occurred
74
// using printStackTrace() method if any
75
[Link]();
76
}
77
}
78
}
Output:
3. Callable Statement:
A CallableStatement is used to execute stored procedures in the
database. Stored procedures are precompiled SQL statements
that can be called with parameters. They are useful for executing
complex operations that involve multiple SQL statements.
Syntax: To create a CallableStatement,
CallableStatement cstmt = [Link]("{call
ProcedureName(?, ?)}");
{call ProcedureName(?, ?)}: Calls a stored procedure
named ProcedureName with placeholders ? for input parameters.
Methods to Execute:
execute(): Executes the stored procedure and returns a
boolean indicating whether the result is a ResultSet (true) or an
update count (false).
executeQuery(): Executes a stored procedure that returns
a ResultSet.
executeUpdate(): Executes a stored procedure that
performs an update and returns the number of rows affected.
Example:
Java
// Java Program illustrating Callable Statement in JDBC
2
// Importing DB(SQL) classes
4
import [Link].*;
5
public class GFG {
7
// Main driver method
9
public static void main(String[] args) {
10
// Try block to check if any exceptions occur
11
try {
12
// Step 1: Load and register the driver
13
[Link]("[Link]");
14
15
// Step 2: Establish a connection
16
Connection con =
[Link]("jdbc:mysql:///world", "root", "12345");
17
18
// Step 3: Create a CallableStatement
19
CallableStatement cs = [Link]("{call GetPeopleInfo()}");
20
21
// Step 4: Execute the stored procedure
22
ResultSet result = [Link]();
23
24
// Step 5: Process the results
25
while ([Link]()) {
26
// Print and display elements (Name and Age)
27
[Link]("Name : " + [Link]("name"));
28
[Link]("Age : " + [Link]("age"));
29
}
30
31
// Step 6: Close resources
32
[Link]();
33
[Link]();
34
[Link]();
35
}
36
// Catch block for SQL exceptions
37
catch (SQLException e) {
38
[Link]();
39
}
40
// Catch block for ClassNotFoundException
41
catch (ClassNotFoundException e) {
42
[Link]();
43
}
44
}
45
}
Output:
Explanation of the Program:
This Java code demonstrates how to use
a CallableStatement in JDBC to execute a stored procedure.
It connects to a MySQL database and prepares
a CallableStatement to call a stored procedure
named peopleinfo with two parameters.
After executing the procedure, it runs a SELECT query to
retrieve and display all records from the people table.
Exception handling is included to manage potential SQL and
class loading errors.
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
Java Memory Management
Last Updated : 14 Dec, 2018
This article will focus on Java memory management, how the
heap works, reference types, garbage collection, and also related
concepts.
Why Learn Java Memory Management?
We all know that Java itself manages the memory and needs no
explicit intervention of the programmer. Garbage collector itself
ensures that the unused space gets cleaned and memory can be
freed when not needed. So what’s the role of programmer and
why a programmer needs to learn about the Java Memory
Management ? Being a programmer, you don’t need to bother
with problems like destroying objects, all credits to the garbage
collector. However the automatic garbage collection doesn’t
guarantee everything. If we don’t know how the memory
management works, often we will end up amidst things that are
not managed by JVM (Java Virtual Machine). There are some
objects that aren’t eligible for the automatic garbage collection.
Hence knowing the memory management is essential as it will
benefit the programmer to write high performance based
programs that will not crash, or if does so, the programmer will
know how to debug or overcome the crashes.
Introduction:
In every programming language, the memory is a vital resource
and is also scarce in nature. Hence it’s essential that the memory
is managed thoroughly without any leaks. Allocation and
deallocation of memory is a critical task and requires a lot of care
and consideration. However in Java, unlike other programming
language, the JVM and to be specific Garbage Collector has the
role of managing memory allocation so that the programmer
needs not to. Whereas in other programming languages such as C
the programmer has direct access to the memory who allocates
memory in his code, thereby creating a lot of scope for leaks.
The major concepts in Java Memory Management :
JVM Memory Structure
Working of Garbage Collector
Java Memory Structure:
JVM defines various run time data area which are used during
execution of a program. Some of the areas are created by the JVM
whereas some are created by the threads that are used in a
program. However, the memory area created by JVM is destroyed
only when the JVM exits. The data areas of thread are created
during instantiation and destroyed when the thread exits.
JVM Memory area parts
Let’s study these parts of memory area in detail:
Heap :
It is a shared runtime data area and stores the actual object
in a memory. It is instantiated during the virtual machine
startup.
This memory is allocated for all class instances and array.
Heap can be of fixed or dynamic size depending upon the
system’s configuration.
JVM provides the user control to initialize or vary the size of
heap as per the requirement. When a new keyword is used,
object is assigned a space in heap, but the reference of the
same exists onto the stack.
There exists one and only one heap for a running JVM
process.
Scanner sc = new Scanner([Link]);
The above statement creates the object of Scanner class which
gets allocated to heap whereas the reference ‘sc’ gets pushed to
the stack.
Note: Garbage collection in heap area is mandatory.
Method Area:
It is a logical part of the heap area and is created on virtual
machine startup.
This memory is allocated for class structures, method data
and constructor field data, and also for interfaces or special
method used in class. Heap can be of fixed or dynamic size
depending upon the system’s configuration.
Can be of a fixed size or expanded as required by the
computation. Needs not to be contiguous.
Note: Though method area is logically a part of heap, it may or
may not be garbage collected even if garbage collection is
compulsory in heap area.
JVM Stacks:
A stack is created at the same time when a thread is created
and is used to store data and partial results which will be
needed while returning value for method and performing
dynamic linking.
Stacks can either be of fixed or dynamic size. The size of a
stack can be chosen independently when it is created.
The memory for stack needs not to be contiguous.
Native method Stacks:
Also called as C stacks, native method stacks are not written in
Java language. This memory is allocated for each thread when its
created. And it can be of fixed or dynamic nature.
Program counter (PC) registers:
Each JVM thread which carries out the task of a specific method
has a program counter register associated with it. The non native
method has a PC which stores the address of the available JVM
instruction whereas in a native method, the value of program
counter is undefined. PC register is capable of storing the return
address or a native pointer on some specific platform.
Working of a Garbage Collector:
JVM triggers this process and as per the JVM garbage
collection process is done or else withheld. It reduces the
burden of programmer by automatically performing the
allocation or deallocation of memory.
Garbage collection process causes the rest of the processes
or threads to be paused and thus is costly in nature. This
problem is unacceptable for the client but can be eliminated by
applying several garbage collector based algorithms. This
process of applying algorithm is often termed as Garbage
Collector tuning and is important for improving the
performance of a program.
Another solution is the generational garbage collectors that
adds an age field to the objects that are assigned a memory.
As more and more objects are created, the list of garbage
grows thereby increasing the garbage collection time. On the
basis of how many clock cycles the objects have survived,
objects are grouped and are allocated an ‘age’ accordingly.
This way the garbage collection work gets distributed.
In the current scenario, all garbage collectors are
generational, and hence, optimal.
Note: [Link]() and [Link]() are the methods which
requests for Garbage collection to JVM explicitly but it doesn’t
ensures garbage collection as the final decision of garbage
collection is of JVM only.
Knowing how the program and it’s data is stored or organized is
essential as it helps when the programmer intends to write an
optimized code in terms of resources and it’s consumption. Also it
helps in finding the memory leaks or inconsistency, and helps in
debugging memory related errors. However, the memory
management concept is extremely vast and therefore one must
put his best to study it as much as possible to improve the
knowledge of the same.
How are Java objects stored in memory?
Last Updated : 28 Dec, 2022
In Java, all objects are dynamically allocated on Heap. This is
different from C++ where objects can be allocated memory either
on Stack or on Heap. In JAVA , when we allocate the object using
new(), the object is allocated on Heap, otherwise on Stack if not
global or static.
In Java, when we only declare a variable of a class type, only a
reference is created (memory is not allocated for the object). To
allocate memory to an object, we must use new(). So the object is
always allocated memory on the heap (See this for more details).
There are two ways to create an object of string in java:
1. By string literal
2. By new keyword
i) By string literal:
This is done using double-quotes.
For example:
String str1="GFG";
String str2="GFG";
By String Literal
Every time when a string literal is created, JVM will check whether
that string already exists in the string constant pool or not. If the
string already exists in the string literal pool then a reference to
the pooled instance is returned. If the string does not exist, then a
new string instance is created in the pool. Hence, only one object
will get created.
Here, the JVM is not bonded to create a new memory.
ii) By new keyword:
This is done using a new keyword.
For example:
String str1=new String("GFG");
String str2=new String("GFG");
By new Keyword
Both str1 and str2 are objects of String.
Every time when a string object is created, JVM will create it in a
heap memory. In this case, the JVM will not check whether the
string already exists or not. If a string already exist , then also for
every string object the memory will get created separately.
Here, the JVM is bond to create a new memory. For example, the
following program fails in the compilation. Compiler gives
error “Error here because t is not initialized”.
java
class Test {
// class contents
void show()
[Link]("Test::show() called");
public class Main {
// Driver Code
public static void main(String[] args)
Test t;
// Error here because t
// is not initialized
[Link]();
Output:
Allocating memory using new() makes the above program work.
java
class Test {
// class contents
void show()
[Link]("Test::show() called");
public class Main {
// Driver Code
public static void main(String[] args)
// all objects are dynamically
// allocated
Test t = new Test();
[Link](); // No error
Output
Test::show() called
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
Stack vs Heap Memory Allocation
Last Updated : 15 Jul, 2024
Memory in a C/C++/Java program can either be allocated on a
stack or a heap.
Prerequisite: Memory layout of C program.
Stack Allocation: The allocation happens on contiguous blocks
of memory. We call it a stack memory allocation because the
allocation happens in the function call stack. The size of memory
to be allocated is known to the compiler and whenever a function
is called, its variables get memory allocated on the stack. And
whenever the function call is over, the memory for the variables is
de-allocated. This all happens using some predefined routines in
the compiler. A programmer does not have to worry about
memory allocation and de-allocation of stack variables. This kind
of memory allocation is also known as Temporary memory
allocation because as soon as the method finishes its execution
all the data belonging to that method flushes out from the stack
automatically. This means any value stored in the stack memory
scheme is accessible as long as the method hasn’t completed its
execution and is currently in a running state.
Key Points:
It’s a temporary memory allocation scheme where the data
members are accessible only if the method( ) that contained
them is currently running.
It allocates or de-allocates the memory automatically as
soon as the corresponding method completes its execution.
We receive the corresponding error Java.
lang. StackOverFlowError by JVM, If the stack memory is filled
completely.
Stack memory allocation is considered safer as compared to
heap memory allocation because the data stored can only be
accessed by the owner thread.
Memory allocation and de-allocation are faster as compared
to Heap-memory allocation.
Stack memory has less storage space as compared to Heap-
memory.
C++
1
int main()
2
{
3
// All these variables get memory
4
// allocated on stack
5
int a;
6
int b[10];
7
int n = 20;
8
int c[n];
9
}
Heap Allocation: The memory is allocated during the execution
of instructions written by programmers. Note that the name heap
has nothing to do with the heap data structure. It is called a heap
because it is a pile of memory space available to programmers to
allocate and de-allocate. Every time when we made an object it
always creates in Heap-space and the referencing information to
these objects is always stored in Stack-memory. Heap memory
allocation isn’t as safe as Stack memory allocation because the
data stored in this space is accessible or visible to all threads. If a
programmer does not handle this memory well, a memory
leak can happen in the program.
The Heap-memory allocation is further divided into three
categories:- These three categories help us to prioritize the
data(Objects) to be stored in the Heap-memory or in the Garbage
collection.
Young Generation – It’s the portion of the memory where
all the new data(objects) are made to allocate the space and
whenever this memory is completely filled then the rest of the
data is stored in Garbage collection.
Old or Tenured Generation – This is the part of Heap-
memory that contains the older data objects that are not in
frequent use or not in use at all are placed.
Permanent Generation – This is the portion of Heap-
memory that contains the JVM’s metadata for the runtime
classes and application methods.
Key Points:
We receive the corresponding error message if Heap-space
is entirely full, java. [Link] by JVM.
This memory allocation scheme is different from the Stack-
space allocation, here no automatic de-allocation feature is
provided. We need to use a Garbage collector to remove the
old unused objects in order to use the memory efficiently.
The processing time(Accessing time) of this memory is quite
slow as compared to Stack-memory.
Heap memory is also not as threaded-safe as Stack-memory
because data stored in Heap-memory are visible to all threads.
The size of the Heap-memory is quite larger as compared to
the Stack-memory.
Heap memory is accessible or exists as long as the whole
application(or java program) runs.
CPP
1
int main()
2
{
3
// This memory for 10 integers
4
// is allocated on heap.
5
int *ptr = new int[10];
6
}
Intermixed example of both kinds of memory allocation
Heap and Stack in java:
C++JavaPythonJavaScript
1
class Emp {
2
int id;
3
String emp_name;
4
5
public Emp(int id, String emp_name) {
6
[Link] = id;
7
this.emp_name = emp_name;
8
}
9
}
10
11
public class Emp_detail {
12
private static Emp Emp_detail(int id, String emp_name) {
13
return new Emp(id, emp_name);
14
}
15
16
public static void main(String[] args) {
17
int id = 21;
18
String name = "Maddy";
19
Emp person_ = null;
20
person_ = Emp_detail(id, name);
21
}
22
}
Following are the conclusions on which we’ll make after
analyzing the above example:
As we start execution of the have program, all the run-time
classes are stored in the Heap-memory space.
Then we find the main() method in the next line which is
stored in the stack along with all its primitive(or local) and the
reference variable Emp of type Emp_detail will also be stored in
the Stack and will point out to the corresponding object stored
in Heap memory.
Then the next line will call to the parameterized constructor
Emp(int, String) from main( ) and it’ll also allocate to the top of
the same stack memory block. This will store:
o The object reference of the invoked object of the stack
memory.
o The primitive value(primitive data type) int id in the
stack memory.
o The reference variable of the String emp_name
argument will point to the actual string from the string
pool into the heap memory.
Then the main method will again call to the Emp_detail()
static method, for which allocation will be made in stack
memory block on top of the previous memory block.
So, for the newly created object Emp of type Emp_detail and
all instance variables will be stored in heap memory.
Pictorial representation as shown in Figure.1 below:
Fig.1
Key Differences Between Stack and Heap Allocations
1. In a stack, the allocation and de-allocation are automatically
done by the compiler whereas, in heap, it needs to be done by
the programmer manually.
1. Handling the Heap frame is costlier than handling the stack
frame.
1. Memory shortage problem is more likely to happen in stack
whereas the main issue in heap memory is fragmentation.
1. Stack frame access is easier than the heap frame as the
stack has a small region of memory and is cache-friendly but in
the case of heap frames which are dispersed throughout the
memory so it causes more cache misses.
1. A stack is not flexible, the memory size allotted cannot be
changed whereas a heap is flexible, and the allotted memory
can be altered.
1. Accessing the time of heap takes is more than a stack.
Comparison Chart
Parameter STACK HEAP
Memory is allocated in a Memory is allocated in any
Basic
contiguous block. random order.
Allocation and De- Automatic by compiler
Manual by the programmer.
allocation instructions.
Cost Less More
Implementation Easy Hard
Access time Faster Slower
Main Issue Shortage of memory Memory fragmentation
Locality of reference Excellent Adequate
Thread safe, data stored can Not Thread safe, data stored
Safety
only be accessed by the owner visible to all threads
Flexibility Fixed-size Resizing is possible
Data type structure Linear Hierarchical
Static memory allocation is Heap memory allocation is
Preferred
preferred in an array. preferred in the linked list.
Parameter STACK HEAP
Size Smaller than heap memory. Larger than stack memory.
Get ready to boost your rank and secure an exceptional
GATE 2025 score with confidence!
Our GATE CS & IT Test Series 2025 offers 60 PYQs
Quizzes, 60 Subject-Wise Mock Tests, 4500+
PYQs and practice questions, and over 20 Full-Length Mock
Tests that ensure you’re well-prepared to tackle the toughest
questions and secure a top-rank in the GATE 2025 exam. Get
personalized insights with student rankings based on performance
and benefit from expert-designed tests created by industry pros
and GATE CS toppers.
Java Virtual Machine (JVM) Stack Area
Last Updated : 20 Jun, 2021
For every thread, JVM creates a separate stack at the time of
thread creation. The memory for a Java Virtual Machine stack
does not need to be contiguous. The Java virtual machine only
performs two operations directly on Java stacks: it pushes and
pops frames. And stack for a particular thread may be termed
as Run – Time Stack. Every method call performed by that
thread is stored in the corresponding run-time stack including
parameters, local variables, intermediate computations, and other
data. After completing a method, the corresponding entry from
the stack is removed. After completing all method calls the stack
becomes empty and that empty stack is destroyed by the JVM just
before terminating the thread. The data stored in the stack is
available for the corresponding thread and not available to the
remaining threads. Hence we can say local data thread-safe. Each
entry in the stack is called Stack Frame or Activation Record.
Stack Frame Structure
The stack frame basically consists of three parts: Local Variable
Array, Operand Stack & Frame Data. When JVM invokes a
Java method, first it checks the class data to determine the
number of words (size of the local variable array and operand
stack, which is measured in words for each individual
method) required by the method in the local variables array and
operand stack. It creates a stack frame of the proper size for
invoked method and pushes it onto the Java stack.
1. Local Variable Array (LVA):
The local variables part of the stack frame is organized as a
zero-based array of words.
It contains all parameters and local variables of the method.
Each slot or entry in the array is of 4 Bytes.
Values of type int, float, and reference occupy 1 entry or slot
in the array i.e. 4 bytes.
Values of double and long occupy 2 consecutive entries in
the array i.e. 8 bytes total.
Byte, short, and char values will be converted to int
type before storing and occupy 1 slot i.e. 4 Bytes.
But the way of storing Boolean values is varied from JVM to
JVM. But most of the JVM gives 1 slot for Boolean values in the
local variable array.
The parameters are placed into the local variable array first,
in the order in which they are declared.
For Example: Let us consider a class Example having a
method bike() then the local variable array will be as shown in
the below diagram:
// Class Declaration
class Example
{
public void bike(int i, long l, float f,
double d, Object o, byte b)
{
}
}
2. Operand Stack (OS):
JVM uses operand stack as workspace like rough work or we
can say for storing intermediate calculation’s result.
The operand stack is organized as an array of words like a
local variable array. But this is not accessed by using an index
like local variable array rather it is accessed by some
instructions that can push the value to the operand stack and
some instructions that can pop values from the operand stack
and some instructions that can perform required operations.
For Example: Here is how a JVM will use this below code
that would subtract two local variables that contain two ints
and store the int result in a third local variable:
So here first two instructions iload_0 and iload_1 will push
the values in the operand stack from a local variable array. And
instruction isub will subtract these two values and store the
result back to the operand stack and after istore_2 the result
will pop out from the operand stack and will store into a local
variable array at position 2.
3. Frame Data (FD):
It contains all symbolic references (constant pool
resolution) and normal method returns related to that
particular method.
It also contains a reference to the Exception table which
provides the corresponding catch block information in the case
of exceptions.
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
How many types of memory areas are
allocated by JVM?
Last Updated : 04 Mar, 2024
JVM (Java Virtual Machine) is an abstract machine, In other words,
it is a program/software which takes Java bytecode and converts
the byte code (line by line) into machine understandable code.
JVM(Java Virtual Machine) acts as a run-time engine to run Java
applications. JVM is the one that actually calls the main
method present in Java code. JVM is a part of the JRE(Java
Runtime Environment).
JVM perform some particular types of operations:
1. Loading of code
1. Verification of code
1. Executing the code
1. It provides a run-time environment to the users
ClassLoader
It is a subsystem of JVM which is used to load class files. It is
mainly responsible for three activities.
Loading
Linking
Initialization
Types of Memory Areas Allocated By the
JVM
All these functions take different forms of memory structure.
The memory in the JVM is divided into 5 different parts:
1. Class(Method) Area
1. Heap
1. Stack
1. Program Counter Register
1. Native Method Stack
Let’s see about them in brief:
1. Class (Method) Area
The class method area is the memory block that stores the class
code, variable code(static variable, runtime constant), method
code, and the constructor of a Java program. (Here method
means the function which is written inside the class). It stores
class-level data of every class such as the runtime constant pool,
field and method data, the code for methods.
2. Heap
The Heap area is the memory block where objects are created or
objects are stored. Heap memory allocates memory for class
interfaces and arrays (an array is an object). It is used to allocate
memory to objects at run time
Note: Static Methods and Variables were previous stored in Class
Area (Till Java 8). But, in current versions of Java static variables
and methods are stored in Heap Memory.
3. Stack
Each thread has a private JVM stack, created at the same time as
the thread. It is used to store data and partial results which will be
needed while returning value for method and performing dynamic
linking.
Java Stack stores frames and a new frame is created each time at
every invocation of the method. A frame is destroyed when its
method invocation completes
4. Program Counter Register:
Each JVM thread that carries out the task of a specific method has
a program counter register associated with it. The non-native
method has a PC that stores the address of the available JVM
instruction whereas, in a native method, the value of the program
counter is undefined. PC register is capable of storing the return
address or a native pointer on some specific platform.
5. Native method Stacks:
Also called C stacks, native method stacks are not written in Java
language. This memory is allocated for each thread when it’s
created And it can be of a fixed or dynamic nature.
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
Garbage Collection in Java
Last Updated : 14 Feb, 2022
Garbage collection in Java is the process by which Java programs
perform automatic memory management. Java programs compile
to bytecode that can be run on a Java Virtual Machine, or JVM for
short. When Java programs run on the JVM, objects are created on
the heap, which is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage
collector finds these unused objects and deletes them to free up
memory.
What is Garbage Collection?
In C/C++, a programmer is responsible for both the creation and
destruction of objects. Usually, programmer neglects the
destruction of useless objects. Due to this negligence, at a certain
point, sufficient memory may not be available to create new
objects, and the entire program will terminate abnormally,
causing OutOfMemoryErrors.
But in Java, the programmer need not care for all those objects
which are no longer in use. Garbage collector destroys these
objects. The main objective of Garbage Collector is to free heap
memory by destroying unreachable objects. The garbage
collector is the best example of the Daemon thread as it is always
running in the background.
How Does Garbage Collection in Java works?
Java garbage collection is an automatic process. Automatic
garbage collection is the process of looking at heap memory,
identifying which objects are in use and which are not, and
deleting the unused objects. An in-use object, or a referenced
object, means that some part of your program still maintains a
pointer to that object. An unused or unreferenced object is no
longer referenced by any part of your program. So the memory
used by an unreferenced object can be reclaimed. The
programmer does not need to mark objects to be deleted
explicitly. The garbage collection implementation lives in the JVM.
Types of Activities in Java Garbage Collection
Two types of garbage collection activity usually happen in Java.
These are:
1. Minor or incremental Garbage Collection: It is said to
have occurred when unreachable objects in the young
generation heap memory are removed.
2. Major or Full Garbage Collection: It is said to have
occurred when the objects that survived the minor garbage
collection are copied into the old generation or permanent
generation heap memory are removed. When compared to the
young generation, garbage collection happens less frequently
in the old generation.
Important Concepts Related to Garbage Collection in
Java
1. Unreachable objects: An object is said to be unreachable if it
doesn’t contain any reference to it. Also, note that objects which
are part of the island of isolation are also unreachable.
Integer i = new Integer(4);
// the new Integer object is reachable via the reference in
'i'
i = null;
// the Integer object is no longer reachable.
2. Eligibility for garbage collection: An object is said to be
eligible for GC(garbage collection) if it is unreachable. After i =
null, integer object 4 in the heap area is suitable for garbage
collection in the above image.
Ways to make an object eligible for Garbage Collector
Even though the programmer is not responsible for
destroying useless objects but it is highly recommended to
make an object unreachable(thus eligible for GC) if it is no
longer required.
There are generally four ways to make an object eligible for
garbage collection.
1. Nullifying the reference variable
2. Re-assigning the reference variable
3. An object created inside the method
4. Island of Isolation
Ways for requesting JVM to run Garbage Collector
Once we make an object eligible for garbage collection, it
may not destroy immediately by the garbage collector.
Whenever JVM runs the Garbage Collector program, then only
the object will be destroyed. But when JVM runs Garbage
Collector, we can not expect.
We can also request JVM to run Garbage Collector. There are
two ways to do it :
1. Using [Link]() method: System class contain
static method gc() for requesting JVM to run Garbage
Collector.
2. Using [Link]().gc() method: Runtim
e class allows the application to interface with the JVM in
which the application is running. Hence by using its gc()
method, we can request JVM to run Garbage Collector.
3. There is no guarantee that any of the above two
methods will run Garbage Collector.
4. The call [Link]() is effectively equivalent to the call
: [Link]().gc()
Finalization
Just before destroying an object, Garbage Collector
calls finalize() method on the object to perform cleanup
activities. Once finalize() method completes, Garbage Collector
destroys that object.
finalize() method is present in Object class with the following
prototype.
protected void finalize() throws Throwable
Based on our requirement, we can override finalize() method for
performing our cleanup activities like closing connection from the
database.
1. The finalize() method is called by Garbage Collector, not
JVM. However, Garbage Collector is one of the modules of JVM.
2. Object class finalize() method has an empty implementation.
Thus, it is recommended to override the finalize() method to
dispose of system resources or perform other cleanups.
3. The finalize() method is never invoked more than once for
any object.
4. If an uncaught exception is thrown by the finalize() method,
the exception is ignored, and the finalization of that object
terminates.
Advantages of Garbage Collection in Java
The advantages of Garbage Collection in Java are:
It makes java memory-efficient because the garbage
collector removes the unreferenced objects from heap
memory.
It is automatically done by the garbage collector(a part of
JVM), so we don’t need extra effort.
Real-World Example
Let’s take a real-life example, where we use the concept of the
garbage collector.
Question: Suppose you go for the internship at GeeksForGeeks,
and you were told to write a program to count the number of
employees working in the company(excluding interns). To make
this program, you have to use the concept of a garbage collector.
This is the actual task you were given at the company:
Write a program to create a class called Employee having the
following data members.
1. An ID for storing unique id allocated to every employee.
2. Name of employee.
3. age of an employee.
Also, provide the following methods:
1. A parameterized constructor to initialize name and age. The
ID should be initialized in this constructor.
2. A method show() to display ID, name, and age.
3. A method showNextId() to display the ID of the next
employee.
Now any beginner, who doesn’t know Garbage Collector in Java
will code like this:
Java
// Java Program to count number
// of employees working
// in a company
class Employee {
private int ID;
private String name;
private int age;
private static int nextId = 1;
// it is made static because it
// is keep common among all and
// shared by all objects
public Employee(String name, int age)
[Link] = name;
[Link] = age;
[Link] = nextId++;
public void show()
[Link]("Id=" + ID + "\nName=" + name
+ "\nAge=" + age);
public void showNextId()
[Link]("Next employee id will be="
+ nextId);
}
class UseEmployee {
public static void main(String[] args)
Employee E = new Employee("GFG1", 56);
Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
{ // It is sub block to keep
// all those interns.
Employee X = new Employee("GFG4", 23);
Employee Y = new Employee("GFG5", 21);
[Link]();
[Link]();
[Link]();
[Link]();
// After countering this brace, X and Y
// will be [Link],
// now it should show nextId as 4.
// Output of this line
[Link]();
// should be 4 but it will give 6 as output.
Output
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=6
Now to get the correct output:
Now garbage collector(gc) will see 2 objects free. Now to
decrement nextId,gc(garbage collector) will call method to
finalize() only when we programmers have overridden it in our
class. And as mentioned previously, we have to request
gc(garbage collector), and for this, we have to write the following
3 steps before closing brace of sub-block.
1. Set references to null(i.e X = Y = null;)
2. Call, [Link]();
3. Call, [Link]();
Now the correct code for counting the number of
employees(excluding interns)
Java
// Correct code to count number
// of employees excluding interns.
class Employee {
private int ID;
private String name;
private int age;
private static int nextId = 1;
// it is made static because it
// is keep common among all and
// shared by all objects
public Employee(String name, int age)
[Link] = name;
[Link] = age;
[Link] = nextId++;
public void show()
[Link]("Id=" + ID + "\nName=" + name
+ "\nAge=" + age);
public void showNextId()
{
[Link]("Next employee id will be="
+ nextId);
protected void finalize()
--nextId;
// In this case,
// gc will call finalize()
// for 2 times for 2 objects.
public class UseEmployee {
public static void main(String[] args)
Employee E = new Employee("GFG1", 56);
Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
// It is sub block to keep
// all those interns.
Employee X = new Employee("GFG4", 23);
Employee Y = new Employee("GFG5", 21);
[Link]();
[Link]();
[Link]();
[Link]();
X = Y = null;
[Link]();
[Link]();
[Link]();
Output
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=4
Related Articles:
How to Make Object Eligible for Garbage Collection in Java?
Island of Isolation in Java
Output of Java programs | Set 10 (Garbage Collection)
How to Find Max Memory, Free Memory , and Total Memory
in Java?
How JVM Works – JVM Architecture?
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
Types of JVM Garbage Collectors in Java
with implementation details
Last Updated : 22 Jan, 2020
prerequisites: Garbage Collection, Mark and Sweep algorithm
Garbage Collection: Garbage collection aka GC is one of the
most important features of Java. Garbage collection is the
mechanism used in Java to de-allocate unused memory, which is
nothing but clear the space consumed by unused objects. To
deallocate unused memory, Garbage collector track all the
objects that are still in use and it marks the rest of the object as
garbage. Basically garbage collector use Mark and Sweep
algorithm to clear unused memory.
Types of Garbage Collection:
The JVM actually provides four different garbage collectors. Each
garbage collector will vary in Application throughput and
Application pause. Application throughput denotes the speed at
which a Java application runs and Application pause means the
time taken by the garbage collector to clean the unused memory
spaces.
1. Serial Garbage Collector: This is the simplest GC
implementation, as it basically works with a single thread. If we
select Serial garbage collector as our default garbage collector
then whenever we will call garbage collector to clean unused
memory then serial garbage collector holds all the running
threads of application i.e. It works by freezing all the
application threads and It will create a single thread to perform
garbage collection. It freezes all other running threads of
application until garbage collection operations have concluded.
If we use Serial Garbage Collector as our default garbage
collector then the application throughput will decrease and
application pause time will increase. As a result, this GC
implementation freezes all application threads when it runs.
Hence, it is not a good idea to use it in multi-threaded
applications like server environments.
Implementation:
If you want to use serial garbage collector, then we have to
explicitly mention while running jar like:
java -XX:+UseSerialGC -jar [Link]
2. Parallel Garbage Collector: Parallel Garbage Collector is
the default garbage collector in Java 8. It is also known
as Throughput collector. Parallel Garbage Collector is same
as Serial Garbage Collector because Parallel Garbage Collector
also freezes the running threads of the application while
performing the garbage collection. But the difference is,
Parallel Garbage Collector uses multiple threads to perform
cleaning of unused heap area. The advantage of using Garbage
Collector as default GC is we can mention few attributes for the
garbage collector, like
How many threads, can garbage collector use to
perform garbage collection.
Implementation:
java -XX:+UseParallelGC -
XX:ParallelGCThreads=NumberOfThreads -jar
[Link]
Maximum pause can garbage collector take while
performing garbage collection
Implementation:
java -XX:+UseParallelGC -
XX:MaxGCPauseMillis=SecInMillisecond -jar
[Link]
3. The parallel garbage collector is far better than serial
garbage collector but one problem with the parallel garbage
collector is it pauses the application during minor operations
also. It is best suited if applications that can handle such
pauses. If we are using JDK 8 then parallel GC is the default
garbage collector.
4. Implementation: If we are running on java 9 and want to
use parallel garbage collector then we should use below
command:
5. java -XX:+UseParallelGC -jar [Link]
6. CMS Garbage collector: CMS Garbage collector is known
as concurrent mark-sweep garbage collector. This garbage
collector uses multiple threads to scan the heap memory
consistently to the mark objects that are unused and then
sweep the marked objects. As we know, Serial garbage
collector and Parallel garbage collector freeze the running
threads of the application while performing the garbage
collection. But CMS Garbage collector will perform freezing of
running threads i.e. application pause in two cases only:
While performing the garbage collection, If there is a
change in heap memory in parallel.
While marking the referenced objects in the old
generation space.
If we compare CMS collector with Parallel garbage collector,
CMS collector uses more CPU to ensure better application
throughput. If we are developing an application where we can
provide more CPU resources for better performance then CMS
garbage collector is the blockquoteferred choice over the
parallel collector. To enable CMS Garbage Collector, we can use
the following argument:
java -XX:+UseParNewGC -jar [Link]
7. G1 Garbage Collector: Firstly G1 Garbage Collector is
introduced in JDK 7. Initially, It was designed to provide better
support for larger heap memory application. G1 Garbage
Collector is the default garbage collection of Java 9. G1
collector replaced the CMS collector since it’s more
performance efficient. How G1 Garbage Collector works is
different from other collectors. Unlike other collectors, the G1
collector partitions the heap space into multiple equal-sized
regions. Basically it is mainly designed for an application
having heap size greater than 4GB. It divides the heap area
into multiple regions vary from 1MB to 32MB. While performing
the garbage collection, G1 Garbage Collector mark the heap
region which has objects that are in use throughout the heap.
By the help of this garbage collector has the information about
the regions that contains most use less objects and garbage
collector first perform the garbage collection on that region
only. Thats why it is known as G first garbage collector. G1 also
does compact the free heap space just after garbage collection
that makes G1 Garbage Collector better than other garbage
collectors. G1 Garbage Collector is the default garbage
collector of Java 9.
Implementation: If we are using Java version less than 9 and
we want to use G1 Garbage Collector then we have to mention
explicitly while running jar file like:
java -XX:+UseG1GC -jar [Link]
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
Stack vs Heap Memory Allocation
Last Updated : 15 Jul, 2024
Memory in a C/C++/Java program can either be allocated on a stack or a
heap.
Prerequisite: Memory layout of C program .
Stack Allocation: The allocation happens on contiguous blocks of
memory. We call it a stack memory allocation because the allocation
happens in the function call stack. The size of memory to be allocated is
known to the compiler and whenever a function is called, its variables get
memory allocated on the stack. And whenever the function call is over,
the memory for the variables is de-allocated. This all happens using some
predefined routines in the compiler. A programmer does not have to worry
about memory allocation and de-allocation of stack variables. This kind of
memory allocation is also known as Temporary memory allocation
because as soon as the method finishes its execution all the data
belonging to that method flushes out from the stack automatically. This
means any value stored in the stack memory scheme is accessible as
long as the method hasn’t completed its execution and is currently in a
running state.
Key Points:
It’s a temporary memory allocation scheme where the data
members are accessible only if the method( ) that contained them is
currently running.
It allocates or de-allocates the memory automatically as soon as the
corresponding method completes its execution.
We receive the corresponding error Java.
lang. StackOverFlowError by JVM, If the stack memory is filled
completely.
Stack memory allocation is considered safer as compared to heap
memory allocation because the data stored can only be accessed by
the owner thread.
Memory allocation and de-allocation are faster as compared to
Heap-memory allocation.
Stack memory has less storage space as compared to Heap-
memory.
C++
1
int main()
2
{
3
// All these variables get memory
4
// allocated on stack
5
int a;
6
int b[10];
7
int n = 20;
8
int c[n];
9
}
Heap Allocation: The memory is allocated during the execution of
instructions written by programmers. Note that the name heap has nothing
to do with the heap data structure. It is called a heap because it is a pile of
memory space available to programmers to allocate and de-allocate.
Every time when we made an object it always creates in Heap-space and
the referencing information to these objects is always stored in Stack-
memory. Heap memory allocation isn’t as safe as Stack memory
allocation because the data stored in this space is accessible or visible to
all threads. If a programmer does not handle this memory well, a memory
leak can happen in the program.
The Heap-memory allocation is further divided into three
categories:- These three categories help us to prioritize the data(Objects)
to be stored in the Heap-memory or in the Garbage collection.
Young Generation – It’s the portion of the memory where all the
new data(objects) are made to allocate the space and whenever this
memory is completely filled then the rest of the data is stored in
Garbage collection.
Old or Tenured Generation – This is the part of Heap-memory that
contains the older data objects that are not in frequent use or not in
use at all are placed.
Permanent Generation – This is the portion of Heap-memory that
contains the JVM’s metadata for the runtime classes and application
methods.
Key Points:
We receive the corresponding error message if Heap-space is
entirely full, java. [Link] by JVM.
This memory allocation scheme is different from the Stack-space
allocation, here no automatic de-allocation feature is provided. We
need to use a Garbage collector to remove the old unused objects in
order to use the memory efficiently.
The processing time(Accessing time) of this memory is quite slow
as compared to Stack-memory.
Heap memory is also not as threaded-safe as Stack-memory
because data stored in Heap-memory are visible to all threads.
The size of the Heap-memory is quite larger as compared to the
Stack-memory.
Heap memory is accessible or exists as long as the whole
application(or java program) runs.
CPP
1
int main()
2
{
3
// This memory for 10 integers
4
// is allocated on heap.
5
int *ptr = new int[10];
6
}
Intermixed example of both kinds of memory allocation Heap and
Stack in java:
C++JavaPythonJavaScript
1
class Emp {
2
int id;
3
String emp_name;
4
5
public Emp(int id, String emp_name) {
6
[Link] = id;
7
this.emp_name = emp_name;
8
}
9
}
10
11
public class Emp_detail {
12
private static Emp Emp_detail(int id, String emp_name) {
13
return new Emp(id, emp_name);
14
}
15
16
public static void main(String[] args) {
17
int id = 21;
18
String name = "Maddy";
19
Emp person_ = null;
20
person_ = Emp_detail(id, name);
21
}
22
}
Following are the conclusions on which we’ll make after analyzing
the above example:
As we start execution of the have program, all the run-time classes
are stored in the Heap-memory space.
Then we find the main() method in the next line which is stored in
the stack along with all its primitive(or local) and the reference variable
Emp of type Emp_detail will also be stored in the Stack and will point
out to the corresponding object stored in Heap memory.
Then the next line will call to the parameterized constructor Emp(int,
String) from main( ) and it’ll also allocate to the top of the same stack
memory block. This will store:
o The object reference of the invoked object of the stack
memory.
o The primitive value(primitive data type ) int id in the stack
memory.
o The reference variable of the String emp_name argument will
point to the actual string from the string pool into the heap
memory.
Then the main method will again call to the Emp_detail() static
method, for which allocation will be made in stack memory block on top
of the previous memory block.
So, for the newly created object Emp of type Emp_detail and all
instance variables will be stored in heap memory.
Pictorial representation as shown in Figure.1 below:
Fig.1
Key Differences Between Stack and Heap Allocations
1. In a stack, the allocation and de-allocation are automatically done
by the compiler whereas, in heap, it needs to be done by the
programmer manually.
1. Handling the Heap frame is costlier than handling the stack frame.
1. Memory shortage problem is more likely to happen in stack whereas
the main issue in heap memory is fragmentation.
1. Stack frame access is easier than the heap frame as the stack has
a small region of memory and is cache-friendly but in the case of heap
frames which are dispersed throughout the memory so it causes more
cache misses.
1. A stack is not flexible, the memory size allotted cannot be changed
whereas a heap is flexible, and the allotted memory can be altered.
1. Accessing the time of heap takes is more than a stack.
Comparison Chart
Parameter STACK HEAP
Memory is allocated in a Memory is allocated in
Basic
contiguous block. any random order.
Allocation and De- Automatic by compiler Manual by the
allocation instructions. programmer.
Cost Less More
Implementation Easy Hard
Access time Faster Slower
Main Issue Shortage of memory Memory fragmentation
Locality of
Excellent Adequate
reference
Thread safe, data stored Not Thread safe, data
Safety can only be accessed by stored visible to all
the owner threads
Flexibility Fixed-size Resizing is possible
Data type structure Linear Hierarchical
Static memory allocation is Heap memory allocation is
Preferred
preferred in an array. preferred in the linked list.
Parameter STACK HEAP
Larger than stack
Size Smaller than heap memory.
memory.
Java Virtual Machine (JVM) Stack Area
Last Updated : 20 Jun, 2021
For every thread, JVM creates a separate stack at the time of
thread creation. The memory for a Java Virtual Machine stack
does not need to be contiguous. The Java virtual machine only
performs two operations directly on Java stacks: it pushes and
pops frames. And stack for a particular thread may be termed
as Run – Time Stack. Every method call performed by that
thread is stored in the corresponding run-time stack including
parameters, local variables, intermediate computations, and other
data. After completing a method, the corresponding entry from
the stack is removed. After completing all method calls the stack
becomes empty and that empty stack is destroyed by the JVM just
before terminating the thread. The data stored in the stack is
available for the corresponding thread and not available to the
remaining threads. Hence we can say local data thread-safe. Each
entry in the stack is called Stack Frame or Activation Record.
Stack Frame Structure
The stack frame basically consists of three parts: Local Variable
Array, Operand Stack & Frame Data. When JVM invokes a
Java method, first it checks the class data to determine the
number of words (size of the local variable array and operand
stack, which is measured in words for each individual
method) required by the method in the local variables array and
operand stack. It creates a stack frame of the proper size for
invoked method and pushes it onto the Java stack.
1. Local Variable Array (LVA):
The local variables part of the stack frame is organized as a
zero-based array of words.
It contains all parameters and local variables of the method.
Each slot or entry in the array is of 4 Bytes.
Values of type int, float, and reference occupy 1 entry or slot
in the array i.e. 4 bytes.
Values of double and long occupy 2 consecutive entries in
the array i.e. 8 bytes total.
Byte, short, and char values will be converted to int
type before storing and occupy 1 slot i.e. 4 Bytes.
But the way of storing Boolean values is varied from JVM to
JVM. But most of the JVM gives 1 slot for Boolean values in the
local variable array.
The parameters are placed into the local variable array first,
in the order in which they are declared.
For Example: Let us consider a class Example having a
method bike() then the local variable array will be as shown in
the below diagram:
// Class Declaration
class Example
{
public void bike(int i, long l, float f,
double d, Object o, byte b)
{
}
}
2. Operand Stack (OS):
JVM uses operand stack as workspace like rough work or we
can say for storing intermediate calculation’s result.
The operand stack is organized as an array of words like a
local variable array. But this is not accessed by using an index
like local variable array rather it is accessed by some
instructions that can push the value to the operand stack and
some instructions that can pop values from the operand stack
and some instructions that can perform required operations.
For Example: Here is how a JVM will use this below code
that would subtract two local variables that contain two ints
and store the int result in a third local variable:
So here first two instructions iload_0 and iload_1 will push
the values in the operand stack from a local variable array. And
instruction isub will subtract these two values and store the
result back to the operand stack and after istore_2 the result
will pop out from the operand stack and will store into a local
variable array at position 2.
3. Frame Data (FD):
It contains all symbolic references (constant pool
resolution) and normal method returns related to that
particular method.
It also contains a reference to the Exception table which
provides the corresponding catch block information in the case
of exceptions.
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
How many types of memory areas are
allocated by JVM?
Last Updated : 04 Mar, 2024
JVM (Java Virtual Machine) is an abstract machine, In other words,
it is a program/software which takes Java bytecode and converts
the byte code (line by line) into machine understandable code.
JVM(Java Virtual Machine) acts as a run-time engine to run Java
applications. JVM is the one that actually calls the main
method present in Java code. JVM is a part of the JRE(Java
Runtime Environment).
JVM perform some particular types of operations:
1. Loading of code
1. Verification of code
1. Executing the code
1. It provides a run-time environment to the users
ClassLoader
It is a subsystem of JVM which is used to load class files. It is
mainly responsible for three activities.
Loading
Linking
Initialization
Types of Memory Areas Allocated By the
JVM
All these functions take different forms of memory structure.
The memory in the JVM is divided into 5 different parts:
1. Class(Method) Area
1. Heap
1. Stack
1. Program Counter Register
1. Native Method Stack
Let’s see about them in brief:
1. Class (Method) Area
The class method area is the memory block that stores the class
code, variable code(static variable, runtime constant), method
code, and the constructor of a Java program. (Here method
means the function which is written inside the class). It stores
class-level data of every class such as the runtime constant pool,
field and method data, the code for methods.
2. Heap
The Heap area is the memory block where objects are created or
objects are stored. Heap memory allocates memory for class
interfaces and arrays (an array is an object). It is used to allocate
memory to objects at run time
Note: Static Methods and Variables were previous stored in Class
Area (Till Java 8). But, in current versions of Java static variables
and methods are stored in Heap Memory.
3. Stack
Each thread has a private JVM stack, created at the same time as
the thread. It is used to store data and partial results which will be
needed while returning value for method and performing dynamic
linking.
Java Stack stores frames and a new frame is created each time at
every invocation of the method. A frame is destroyed when its
method invocation completes
4. Program Counter Register:
Each JVM thread that carries out the task of a specific method has
a program counter register associated with it. The non-native
method has a PC that stores the address of the available JVM
instruction whereas, in a native method, the value of the program
counter is undefined. PC register is capable of storing the return
address or a native pointer on some specific platform.
5. Native method Stacks:
Also called C stacks, native method stacks are not written in Java
language. This memory is allocated for each thread when it’s
created And it can be of a fixed or dynamic nature.
Garbage Collection in Java
Last Updated : 14 Feb, 2022
Garbage collection in Java is the process by which Java programs
perform automatic memory management. Java programs compile
to bytecode that can be run on a Java Virtual Machine, or JVM for
short. When Java programs run on the JVM, objects are created on
the heap, which is a portion of memory dedicated to the program.
Eventually, some objects will no longer be needed. The garbage
collector finds these unused objects and deletes them to free up
memory.
What is Garbage Collection?
In C/C++, a programmer is responsible for both the creation and
destruction of objects. Usually, programmer neglects the
destruction of useless objects. Due to this negligence, at a certain
point, sufficient memory may not be available to create new
objects, and the entire program will terminate abnormally,
causing OutOfMemoryErrors.
But in Java, the programmer need not care for all those objects
which are no longer in use. Garbage collector destroys these
objects. The main objective of Garbage Collector is to free heap
memory by destroying unreachable objects. The garbage
collector is the best example of the Daemon thread as it is always
running in the background.
How Does Garbage Collection in Java works?
Java garbage collection is an automatic process. Automatic
garbage collection is the process of looking at heap memory,
identifying which objects are in use and which are not, and
deleting the unused objects. An in-use object, or a referenced
object, means that some part of your program still maintains a
pointer to that object. An unused or unreferenced object is no
longer referenced by any part of your program. So the memory
used by an unreferenced object can be reclaimed. The
programmer does not need to mark objects to be deleted
explicitly. The garbage collection implementation lives in the JVM.
Types of Activities in Java Garbage Collection
Two types of garbage collection activity usually happen in Java.
These are:
1. Minor or incremental Garbage Collection: It is said to
have occurred when unreachable objects in the young
generation heap memory are removed.
2. Major or Full Garbage Collection: It is said to have
occurred when the objects that survived the minor garbage
collection are copied into the old generation or permanent
generation heap memory are removed. When compared to the
young generation, garbage collection happens less frequently
in the old generation.
Important Concepts Related to Garbage Collection in
Java
1. Unreachable objects: An object is said to be unreachable if it
doesn’t contain any reference to it. Also, note that objects which
are part of the island of isolation are also unreachable.
Integer i = new Integer(4);
// the new Integer object is reachable via the reference in
'i'
i = null;
// the Integer object is no longer reachable.
2. Eligibility for garbage collection: An object is said to be
eligible for GC(garbage collection) if it is unreachable. After i =
null, integer object 4 in the heap area is suitable for garbage
collection in the above image.
Ways to make an object eligible for Garbage Collector
Even though the programmer is not responsible for
destroying useless objects but it is highly recommended to
make an object unreachable(thus eligible for GC) if it is no
longer required.
There are generally four ways to make an object eligible for
garbage collection.
1. Nullifying the reference variable
2. Re-assigning the reference variable
3. An object created inside the method
4. Island of Isolation
Ways for requesting JVM to run Garbage Collector
Once we make an object eligible for garbage collection, it
may not destroy immediately by the garbage collector.
Whenever JVM runs the Garbage Collector program, then only
the object will be destroyed. But when JVM runs Garbage
Collector, we can not expect.
We can also request JVM to run Garbage Collector. There are
two ways to do it :
1. Using [Link]() method: System class contain
static method gc() for requesting JVM to run Garbage
Collector.
2. Using [Link]().gc() method: Runtim
e class allows the application to interface with the JVM in
which the application is running. Hence by using its gc()
method, we can request JVM to run Garbage Collector.
3. There is no guarantee that any of the above two
methods will run Garbage Collector.
4. The call [Link]() is effectively equivalent to the call
: [Link]().gc()
Finalization
Just before destroying an object, Garbage Collector
calls finalize() method on the object to perform cleanup
activities. Once finalize() method completes, Garbage Collector
destroys that object.
finalize() method is present in Object class with the following
prototype.
protected void finalize() throws Throwable
Based on our requirement, we can override finalize() method for
performing our cleanup activities like closing connection from the
database.
1. The finalize() method is called by Garbage Collector, not
JVM. However, Garbage Collector is one of the modules of JVM.
2. Object class finalize() method has an empty implementation.
Thus, it is recommended to override the finalize() method to
dispose of system resources or perform other cleanups.
3. The finalize() method is never invoked more than once for
any object.
4. If an uncaught exception is thrown by the finalize() method,
the exception is ignored, and the finalization of that object
terminates.
Advantages of Garbage Collection in Java
The advantages of Garbage Collection in Java are:
It makes java memory-efficient because the garbage
collector removes the unreferenced objects from heap
memory.
It is automatically done by the garbage collector(a part of
JVM), so we don’t need extra effort.
Real-World Example
Let’s take a real-life example, where we use the concept of the
garbage collector.
Question: Suppose you go for the internship at GeeksForGeeks,
and you were told to write a program to count the number of
employees working in the company(excluding interns). To make
this program, you have to use the concept of a garbage collector.
This is the actual task you were given at the company:
Write a program to create a class called Employee having the
following data members.
1. An ID for storing unique id allocated to every employee.
2. Name of employee.
3. age of an employee.
Also, provide the following methods:
1. A parameterized constructor to initialize name and age. The
ID should be initialized in this constructor.
2. A method show() to display ID, name, and age.
3. A method showNextId() to display the ID of the next
employee.
Now any beginner, who doesn’t know Garbage Collector in Java
will code like this:
Java
// Java Program to count number
// of employees working
// in a company
class Employee {
private int ID;
private String name;
private int age;
private static int nextId = 1;
// it is made static because it
// is keep common among all and
// shared by all objects
public Employee(String name, int age)
[Link] = name;
[Link] = age;
[Link] = nextId++;
public void show()
[Link]("Id=" + ID + "\nName=" + name
+ "\nAge=" + age);
public void showNextId()
[Link]("Next employee id will be="
+ nextId);
}
class UseEmployee {
public static void main(String[] args)
Employee E = new Employee("GFG1", 56);
Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
{ // It is sub block to keep
// all those interns.
Employee X = new Employee("GFG4", 23);
Employee Y = new Employee("GFG5", 21);
[Link]();
[Link]();
[Link]();
[Link]();
// After countering this brace, X and Y
// will be [Link],
// now it should show nextId as 4.
// Output of this line
[Link]();
// should be 4 but it will give 6 as output.
Output
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=6
Now to get the correct output:
Now garbage collector(gc) will see 2 objects free. Now to
decrement nextId,gc(garbage collector) will call method to
finalize() only when we programmers have overridden it in our
class. And as mentioned previously, we have to request
gc(garbage collector), and for this, we have to write the following
3 steps before closing brace of sub-block.
1. Set references to null(i.e X = Y = null;)
2. Call, [Link]();
3. Call, [Link]();
Now the correct code for counting the number of
employees(excluding interns)
Java
// Correct code to count number
// of employees excluding interns.
class Employee {
private int ID;
private String name;
private int age;
private static int nextId = 1;
// it is made static because it
// is keep common among all and
// shared by all objects
public Employee(String name, int age)
[Link] = name;
[Link] = age;
[Link] = nextId++;
public void show()
[Link]("Id=" + ID + "\nName=" + name
+ "\nAge=" + age);
public void showNextId()
{
[Link]("Next employee id will be="
+ nextId);
protected void finalize()
--nextId;
// In this case,
// gc will call finalize()
// for 2 times for 2 objects.
public class UseEmployee {
public static void main(String[] args)
Employee E = new Employee("GFG1", 56);
Employee F = new Employee("GFG2", 45);
Employee G = new Employee("GFG3", 25);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
// It is sub block to keep
// all those interns.
Employee X = new Employee("GFG4", 23);
Employee Y = new Employee("GFG5", 21);
[Link]();
[Link]();
[Link]();
[Link]();
X = Y = null;
[Link]();
[Link]();
[Link]();
Output
Id=1
Name=GFG1
Age=56
Id=2
Name=GFG2
Age=45
Id=3
Name=GFG3
Age=25
Next employee id will be=4
Next employee id will be=4
Next employee id will be=4
Id=4
Name=GFG4
Age=23
Id=5
Name=GFG5
Age=21
Next employee id will be=6
Next employee id will be=6
Next employee id will be=4
Related Articles:
How to Make Object Eligible for Garbage Collection in Java?
Island of Isolation in Java
Output of Java programs | Set 10 (Garbage Collection)
How to Find Max Memory, Free Memory , and Total Memory
in Java?
How JVM Works – JVM Architecture?
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
Types of JVM Garbage Collectors in Java
with implementation details
Last Updated : 22 Jan, 2020
prerequisites: Garbage Collection, Mark and Sweep algorithm
Garbage Collection: Garbage collection aka GC is one of the
most important features of Java. Garbage collection is the
mechanism used in Java to de-allocate unused memory, which is
nothing but clear the space consumed by unused objects. To
deallocate unused memory, Garbage collector track all the
objects that are still in use and it marks the rest of the object as
garbage. Basically garbage collector use Mark and Sweep
algorithm to clear unused memory.
Types of Garbage Collection:
The JVM actually provides four different garbage collectors. Each
garbage collector will vary in Application throughput and
Application pause. Application throughput denotes the speed at
which a Java application runs and Application pause means the
time taken by the garbage collector to clean the unused memory
spaces.
1. Serial Garbage Collector: This is the simplest GC
implementation, as it basically works with a single thread. If we
select Serial garbage collector as our default garbage collector
then whenever we will call garbage collector to clean unused
memory then serial garbage collector holds all the running
threads of application i.e. It works by freezing all the
application threads and It will create a single thread to perform
garbage collection. It freezes all other running threads of
application until garbage collection operations have concluded.
If we use Serial Garbage Collector as our default garbage
collector then the application throughput will decrease and
application pause time will increase. As a result, this GC
implementation freezes all application threads when it runs.
Hence, it is not a good idea to use it in multi-threaded
applications like server environments.
Implementation:
If you want to use serial garbage collector, then we have to
explicitly mention while running jar like:
java -XX:+UseSerialGC -jar [Link]
2. Parallel Garbage Collector: Parallel Garbage Collector is
the default garbage collector in Java 8. It is also known
as Throughput collector. Parallel Garbage Collector is same
as Serial Garbage Collector because Parallel Garbage Collector
also freezes the running threads of the application while
performing the garbage collection. But the difference is,
Parallel Garbage Collector uses multiple threads to perform
cleaning of unused heap area. The advantage of using Garbage
Collector as default GC is we can mention few attributes for the
garbage collector, like
How many threads, can garbage collector use to
perform garbage collection.
Implementation:
java -XX:+UseParallelGC -
XX:ParallelGCThreads=NumberOfThreads -jar
[Link]
Maximum pause can garbage collector take while
performing garbage collection
Implementation:
java -XX:+UseParallelGC -
XX:MaxGCPauseMillis=SecInMillisecond -jar
[Link]
3. The parallel garbage collector is far better than serial
garbage collector but one problem with the parallel garbage
collector is it pauses the application during minor operations
also. It is best suited if applications that can handle such
pauses. If we are using JDK 8 then parallel GC is the default
garbage collector.
4. Implementation: If we are running on java 9 and want to
use parallel garbage collector then we should use below
command:
5. java -XX:+UseParallelGC -jar [Link]
6. CMS Garbage collector: CMS Garbage collector is known
as concurrent mark-sweep garbage collector. This garbage
collector uses multiple threads to scan the heap memory
consistently to the mark objects that are unused and then
sweep the marked objects. As we know, Serial garbage
collector and Parallel garbage collector freeze the running
threads of the application while performing the garbage
collection. But CMS Garbage collector will perform freezing of
running threads i.e. application pause in two cases only:
While performing the garbage collection, If there is a
change in heap memory in parallel.
While marking the referenced objects in the old
generation space.
If we compare CMS collector with Parallel garbage collector,
CMS collector uses more CPU to ensure better application
throughput. If we are developing an application where we can
provide more CPU resources for better performance then CMS
garbage collector is the blockquoteferred choice over the
parallel collector. To enable CMS Garbage Collector, we can use
the following argument:
java -XX:+UseParNewGC -jar [Link]
7. G1 Garbage Collector: Firstly G1 Garbage Collector is
introduced in JDK 7. Initially, It was designed to provide better
support for larger heap memory application. G1 Garbage
Collector is the default garbage collection of Java 9. G1
collector replaced the CMS collector since it’s more
performance efficient. How G1 Garbage Collector works is
different from other collectors. Unlike other collectors, the G1
collector partitions the heap space into multiple equal-sized
regions. Basically it is mainly designed for an application
having heap size greater than 4GB. It divides the heap area
into multiple regions vary from 1MB to 32MB. While performing
the garbage collection, G1 Garbage Collector mark the heap
region which has objects that are in use throughout the heap.
By the help of this garbage collector has the information about
the regions that contains most use less objects and garbage
collector first perform the garbage collection on that region
only. Thats why it is known as G first garbage collector. G1 also
does compact the free heap space just after garbage collection
that makes G1 Garbage Collector better than other garbage
collectors. G1 Garbage Collector is the default garbage
collector of Java 9.
Implementation: If we are using Java version less than 9 and
we want to use G1 Garbage Collector then we have to mention
explicitly while running jar file like:
java -XX:+UseG1GC -jar [Link]
Want to be a master in Backend Development with Java for
building robust and scalable applications? Enroll in Java Backend
and Development Live Course by GeeksforGeeks to get your
hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration,
and more through hands-on experiences and live projects. Are
you new to Backend development or want to be a Java Pro? This
course equips you with all you need for building high-
performance, heavy-loaded backend systems in Java. Ready to
take your Java Backend skills to the next level? Enroll now and
take your development career to sky highs.
Stack vs Heap Memory Allocation
Last Updated : 15 Jul, 2024
Memory in a C/C++/Java program can either be allocated on a
stack or a heap.
Prerequisite: Memory layout of C program.
Stack Allocation: The allocation happens on contiguous blocks
of memory. We call it a stack memory allocation because the
allocation happens in the function call stack. The size of memory
to be allocated is known to the compiler and whenever a function
is called, its variables get memory allocated on the stack. And
whenever the function call is over, the memory for the variables is
de-allocated. This all happens using some predefined routines in
the compiler. A programmer does not have to worry about
memory allocation and de-allocation of stack variables. This kind
of memory allocation is also known as Temporary memory
allocation because as soon as the method finishes its execution
all the data belonging to that method flushes out from the stack
automatically. This means any value stored in the stack memory
scheme is accessible as long as the method hasn’t completed its
execution and is currently in a running state.
Key Points:
It’s a temporary memory allocation scheme where the data
members are accessible only if the method( ) that contained
them is currently running.
It allocates or de-allocates the memory automatically as
soon as the corresponding method completes its execution.
We receive the corresponding error Java.
lang. StackOverFlowError by JVM, If the stack memory is filled
completely.
Stack memory allocation is considered safer as compared to
heap memory allocation because the data stored can only be
accessed by the owner thread.
Memory allocation and de-allocation are faster as compared
to Heap-memory allocation.
Stack memory has less storage space as compared to Heap-
memory.
C++
1
int main()
2
{
3
// All these variables get memory
4
// allocated on stack
5
int a;
6
int b[10];
7
int n = 20;
8
int c[n];
9
}
Heap Allocation: The memory is allocated during the execution
of instructions written by programmers. Note that the name heap
has nothing to do with the heap data structure. It is called a heap
because it is a pile of memory space available to programmers to
allocate and de-allocate. Every time when we made an object it
always creates in Heap-space and the referencing information to
these objects is always stored in Stack-memory. Heap memory
allocation isn’t as safe as Stack memory allocation because the
data stored in this space is accessible or visible to all threads. If a
programmer does not handle this memory well, a memory
leak can happen in the program.
The Heap-memory allocation is further divided into three
categories:- These three categories help us to prioritize the
data(Objects) to be stored in the Heap-memory or in the Garbage
collection.
Young Generation – It’s the portion of the memory where
all the new data(objects) are made to allocate the space and
whenever this memory is completely filled then the rest of the
data is stored in Garbage collection.
Old or Tenured Generation – This is the part of Heap-
memory that contains the older data objects that are not in
frequent use or not in use at all are placed.
Permanent Generation – This is the portion of Heap-
memory that contains the JVM’s metadata for the runtime
classes and application methods.
Key Points:
We receive the corresponding error message if Heap-space
is entirely full, java. [Link] by JVM.
This memory allocation scheme is different from the Stack-
space allocation, here no automatic de-allocation feature is
provided. We need to use a Garbage collector to remove the
old unused objects in order to use the memory efficiently.
The processing time(Accessing time) of this memory is quite
slow as compared to Stack-memory.
Heap memory is also not as threaded-safe as Stack-memory
because data stored in Heap-memory are visible to all threads.
The size of the Heap-memory is quite larger as compared to
the Stack-memory.
Heap memory is accessible or exists as long as the whole
application(or java program) runs.
CPP
1
int main()
2
{
3
// This memory for 10 integers
4
// is allocated on heap.
5
int *ptr = new int[10];
6
}
Intermixed example of both kinds of memory allocation
Heap and Stack in java:
C++JavaPythonJavaScript
1
class Emp {
2
int id;
3
String emp_name;
4
5
public Emp(int id, String emp_name) {
6
[Link] = id;
7
this.emp_name = emp_name;
8
}
9
}
10
11
public class Emp_detail {
12
private static Emp Emp_detail(int id, String emp_name) {
13
return new Emp(id, emp_name);
14
}
15
16
public static void main(String[] args) {
17
int id = 21;
18
String name = "Maddy";
19
Emp person_ = null;
20
person_ = Emp_detail(id, name);
21
}
22
}
Following are the conclusions on which we’ll make after
analyzing the above example:
As we start execution of the have program, all the run-time
classes are stored in the Heap-memory space.
Then we find the main() method in the next line which is
stored in the stack along with all its primitive(or local) and the
reference variable Emp of type Emp_detail will also be stored in
the Stack and will point out to the corresponding object stored
in Heap memory.
Then the next line will call to the parameterized constructor
Emp(int, String) from main( ) and it’ll also allocate to the top of
the same stack memory block. This will store:
o The object reference of the invoked object of the stack
memory.
o The primitive value(primitive data type) int id in the
stack memory.
o The reference variable of the String emp_name
argument will point to the actual string from the string
pool into the heap memory.
Then the main method will again call to the Emp_detail()
static method, for which allocation will be made in stack
memory block on top of the previous memory block.
So, for the newly created object Emp of type Emp_detail and
all instance variables will be stored in heap memory.
Pictorial representation as shown in Figure.1 below:
Fig.1
Key Differences Between Stack and Heap Allocations
1. In a stack, the allocation and de-allocation are automatically
done by the compiler whereas, in heap, it needs to be done by
the programmer manually.
1. Handling the Heap frame is costlier than handling the stack
frame.
1. Memory shortage problem is more likely to happen in stack
whereas the main issue in heap memory is fragmentation.
1. Stack frame access is easier than the heap frame as the
stack has a small region of memory and is cache-friendly but in
the case of heap frames which are dispersed throughout the
memory so it causes more cache misses.
1. A stack is not flexible, the memory size allotted cannot be
changed whereas a heap is flexible, and the allotted memory
can be altered.
1. Accessing the time of heap takes is more than a stack.
Comparison Chart
Parameter STACK HEAP
Memory is allocated in a Memory is allocated in any
Basic
contiguous block. random order.
Allocation and De- Automatic by compiler
Manual by the programmer.
allocation instructions.
Cost Less More
Implementation Easy Hard
Access time Faster Slower
Main Issue Shortage of memory Memory fragmentation
Locality of reference Excellent Adequate
Thread safe, data stored can Not Thread safe, data stored
Safety
only be accessed by the owner visible to all threads
Flexibility Fixed-size Resizing is possible
Data type structure Linear Hierarchical
Static memory allocation is Heap memory allocation is
Preferred
preferred in an array. preferred in the linked list.
Parameter STACK HEAP
Size Smaller than heap memory. Larger than stack memory.
Get ready to boost your rank and secure an exceptional
GATE 2025 score with confidence!
Our GATE CS & IT Test Series 2025 offers 60 PYQs
Quizzes, 60 Subject-Wise Mock Tests, 4500+
PYQs and practice questions, and over 20 Full-Length Mock
Tests that ensure you’re well-prepared to tackle the toughest
questions and secure a top-rank in the GATE 2025 exam. Get
personalized insights with student rankings based on performance
and benefit from expert-designed tests created by industry pros
and GATE CS toppers.
[Link]
ref=next_article
[Link]
JDBC - Create Database
Previous
Next
This tutorial provides examples on how to create a Database and Schema
using JDBC application. Before executing the following example, make
sure you have the following in place −
You should have admin privilege to create a database in the given
schema. To execute the following example, you need to replace
the username and password with your actual user name and
password.
Your MySQL or whatever database is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with the database
server.
To create a new database, you need not give any database name
while preparing database URL as mentioned in the below example.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to the database.
Clean up the environment . try with resources automatically
closes the resources.
Example: Creating a Database
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've created a Statement
object using [Link]() method. Then using
[Link](), we've run the query to create a new
database named Students and printed the success message.
In case of any exception while creating the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
){
String sql = "CREATE DATABASE STUDENTS";
[Link](sql);
[Link]("Database created successfully...");
} catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Database created successfully...
C:\>
As we've successfully created the database, on similar lines, we can
create the schema as well as shown in example below:
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Creating a Schema
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've created a Statement
object using [Link]() method. Then using
[Link](), we've run the query to create a new schema
named Sample_db1 and printed the success message.
In case of any exception while creating the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
){
String sql = "CREATE SCHEMA Sample_db1";
[Link](sql);
[Link]("Schema created successfully...");
} catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Schema created successfully...
C:\>
JDBC - Select Database
Previous
Next
This chapter provides examples on how to select a Database using JDBC
application. Before executing the following example, make sure you have
the following in place −
To execute the following example you need to replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using, is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for the database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with
a selected database.
Selection of database is made while you prepare database URL.
Following example would make connection
with STUDENTS database.
Clean up the environment − try with resources automatically
closes the resources.
Example: Selecting a Database
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've printed the success
message.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
[Link]("Connecting to a selected database...");
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);) {
[Link]("Connected database successfully...");
} catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
C:\>
As we've seen how to connect to the database, in following example, we'll
get data from the table of the connected database.
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Getting Records from a Table of
Selected Database
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've created a Statement
object using [Link]() method.
The list of databases is first displayed using "SHOW DATABASES"
command. Then, the SQL command "USE TUTORIALSPOINT" is used to
select a database. Then, a SQL query is issued on table "EMPLOYEES", to
demonstrate that the mentioned database is in use.
In case of any exception while creating the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of selecting a database.
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);) {
[Link]("Connected database successfully...");
Statement stmt = [Link]();
ResultSet rs1 = [Link]("SHOW DATABASES");
[Link]("DATABASES");
[Link]("-------------------------------------------");
while( [Link]()){
[Link]([Link](1));
}
[Link]("-------------------------------------------------------");
// The line below SELECTS a database TUTORIALSPOINT
[Link]("use TUTORIALSPOINT");
ResultSet rs2 = [Link]("select * from employees");
[Link]("Id of employees");
while ([Link]()){
[Link]("id= " + [Link]("id"));
}
} catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Connected database successfully..
DATABASES
-------------------------------------
information_schema
mysql
performance_schema
sample_db1
students
sys
tutorialspoint
tutorialspoint_copy
world
-------------------------------------------------------
Id of employees
id= 1
id= 2
id= 3
id= 4
id= 7
id= 8
id= 21
id= 22
id= 25
id= 26
id= 34
id= 35
id= 36
id= 37
C:\>
Let's explore other commands like to show tables in the selected database
in example below.
Example: Getting Current Database and Table
Names of Selected Database
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've created a Statement
object using [Link]() method.
The SQL command "USE TUTORIALSPOINT" is used to select a database.
Now using "SELECT DATABASE()", we're printing the current database
selected. Then, a SQL query is issued "SHOW TABLES", to show the tables
of the connected database.
In case of any exception while creating the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of SELECT DATABASE() command and
SHOW TABLES
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
// TODO code application logic here
try(Connection conn = [Link](DB_URL, USER,
PASS);) {
[Link]("Connected database successfully...");
Statement stmt = [Link]();
// This statement will make TUTORIALSPOINT as the current
database.
[Link]("use TUTORIALSPOINT");
// This will tell us which is the selected database
ResultSet rs1 = [Link]("SELECT DATABASE()");
while( [Link]()){
[Link]("Current database: " + [Link](1));
}
ResultSet rs2 = [Link]("SHOW TABLES");
[Link]("List of tables in current database
TUTORIALSPOINT");
[Link]("---------------------------------------------------");
while([Link]()){
[Link]( [Link](1));
}
}catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Connected database successfully...
Current database: tutorialspoint
List of tables in current database TUTORIALSPOINT
---------------------------------------------------
employees
jdbc_blob_clob
officers
students
JDBC - Drop Database
Previous
Next
This chapter provides examples on how to drop an existing Database using JDBC application
and MySQLAdmin console. Before executing the following example, make sure you have the
following in place −
To execute the following example you need to replace
the username and password with your actual user name and password.
Your MySQL is up and running.
NOTE: This is a serious operation and you have to make a firm decision before proceeding
to delete a database because everything you have in your database would be lost.
Required Steps
The following steps are required to create a new Database using JDBC application −
Import the packages − Requires that you include the packages containing the
JDBC classes needed for database programming. Most often, using import
[Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection object, which
represents a physical connection with a database server.
Deleting a database does not require database name to be in your database URL.
Following example would delete STUDENTS database.
Execute a query − Requires using an object of type Statement for building and
submitting an SQL statement to delete the database.
Clean up the environment − try with resources automatically closes the
resources.
Example: Dropping a Database
In this example, we've three static strings containing a dababase connection url, username,
password. Now using [Link]() method, we've prepared a database
connection. Once connection is prepared, we've created a Statement object using
[Link]() method. Then using [Link](), we've run the
query to drop a database named Students and printed the success message.
In case of any exception while creating the database, a catch block handled SQLException
and printed the stack trace.
Copy and paste the following example in [Link], compile and run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
){
String sql = "DROP DATABASE STUDENTS";
[Link](sql);
[Link]("Database dropped successfully...");
} catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Database dropped successfully...
C:\>
In next example, we're dropping a database TUTORIALSPOINT_COPY. Before deleting,
we're showing all available databases and then after deleting the same list is reprinted to
check if database is dropped or not. See the example below using JDBC code:
Explore our latest online courses and learn new skills at your own pace. Enroll and
become a certified expert to boost your career.
Example: Dropping a Database
In this example, we've three static strings containing a dababase connection url, username,
password. Now using [Link]() method, we've prepared a database
connection. Once connection is prepared, we've created a Statement object using
[Link]() method.
The SQL command "SHOW DATABASES" is used to show list of available databases. Now
using "DROP DATABASE TUTORIALSPOINT_COPY", we're dropping the
TUTORIALSPOINT_COPY database. Then, again SQL query is issued "SHOW
DATABASES", to show the updated list of databases.
In case of any exception while creating the database, a catch block handled SQLException
and printed the stack trace.
Copy and paste the following example in [Link], compile and run as follows −
import [Link].*;
// Drop database example
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String args[]) {
try(Connection conn = [Link](DB_URL, USER,
PASS);) {
[Link]("Connected to database successfully...");
Statement stmt = [Link]();
ResultSet rs1 = [Link]("SHOW DATABASES");
[Link]("DATABASES");
[Link]("-------------------------------------------");
while( [Link]()){
[Link]([Link](1));
}
//Now DROP DATABASE
int r = [Link]("DROP DATABASE
TUTORIALSPOINT_COPY");
[Link]("TutorialsPoint_copy database successfully
deleted. No. of tables removed = " + r);
[Link]("-------------------------------------------");
ResultSet rs2 = [Link]("SHOW DATABASES");
[Link]("DATABASES after DROP DATABASE has been
called.");
[Link]("-------------------------------------------");
while( [Link]()){
[Link]([Link](1));
}
}catch(SQLException e){
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Connected to database successfully...
DATABASES
-------------------------------------------
information_schema
mysql
performance_schema
sample_db1
students
sys
tutorialspoint
tutorialspoint_copy
world
TutorialsPoint_copy database successfully deleted. No. of tables removed = 4
-------------------------------------------
DATABASES after DROP DATABASE has been called.
-------------------------------------------
information_schema
mysql
performance_schema
sample_db1
students
sys
tutorialspoint
world
C:\>
Another way to delete a database is through mysqladmin console. From command prompt, go
to the bin directory of MySQL installation directory. For example:
C:\Program Files\MySQL\MySQL Server 8.4\bin>
From this directory, type: following command
C:\Program Files\MySQL\MySQL Server 8.4\bin> mysqladmin -u root -p drop
sample_db1
Once you type this, you will be asked for password. Enter the password for user 'root'.
After dropping, type SHOW DATABASES in MySQL prompt. The database removed will
not show. See screenshot below:
Print Page
JDBC - Create Table
Previous
Next
This chapter provides examples on how to create table, temporary table
and duplicate table using JDBC application. Before executing the following
example, make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to create a table in a
seleted database.
Clean up the environment − try with resources automatically
closes the resources.
Example: Creating a Table
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared a
SQL string to create a new table REGISTRATION and created the table in
database by calling [Link]() method.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile
and run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
){
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
[Link](sql);
[Link]("Created table in given database...");
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Created table in given database...
C:\>
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Creating a Temporary Table
We can create a temporary table, which exists only during an active
session. Temporary tables are supported in MySQL, SQL Server, Oracle
etc.
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared a
SQL string to create a new Temporary table EMPLOYEES_COPY and
created the table in database by calling [Link]() method.
In next line of code, we've created a query string to get all records from
the newly created temporary table EMPLOYEES_COPY. Query is fired using
[Link]() method and result is stored in a ResultSet.
ResultSet is iterated to print all the employees.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile
and run as follows −
import [Link].*;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
String QUERY1 = "CREATE TEMPORARY TABLE EMPLOYEES_COPY
SELECT * FROM EMPLOYEES";
[Link](QUERY1);
String QUERY2 = "SELECT * FROM EMPLOYEES_COPY";
ResultSet rs = [Link](QUERY2);
while ([Link]()){
[Link]("Id: " + [Link]("id"));
[Link](" Age: " + [Link]("age"));
[Link](" First: " + [Link]("first"));
[Link](" Last: " + [Link]("last"));
[Link]("------------------------------------------");
}
}catch (SQLException e){
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Id: 1 Age: 18 First: Zara Last: Ali
------------------------------------------
Id: 2 Age: 25 First: Mahnaz Last: Fatma
------------------------------------------
Id: 3 Age: 20 First: Zaid Last: Khan
------------------------------------------
Id: 4 Age: 28 First: Sumit Last: Mittal
------------------------------------------
Id: 7 Age: 20 First: Rita Last: Tez
-----------------------------------------
Id: 8 Age: 20 First: Sita Last: Singh
------------------------------------------
Id: 21 Age: 35 First: Jeevan Last: Rao
------------------------------------------
Id: 22 Age: 40 First: Aditya Last: Chaube
------------------------------------------
Id: 25 Age: 35 First: Jeevan Last: Rao
------------------------------------------
Id: 26 Age: 35 First: Aditya Last: Chaube
------------------------------------------
Id: 34 Age: 45 First: Ahmed Last: Ali
------------------------------------------
Id: 35 Age: 50 First: Raksha Last: Agarwal
------------------------------------------
C:\>
Example: Creating a Duplicate Table
We can create a TABLE which is exactly similar to an existing table. The
syntax is:
CREATE new_table_name LIKE orig_table_name;
After executing the command, all data from original table is copied to new
table.
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared a
SQL string to create a new duplicate table EMPLOYEES_O and created the
table in database by calling [Link]() method.
In next line of code, we've created a query string to get all records from
the newly created duplicate table EMPLOYEES_O. Query is fired using
[Link]() method and result is stored in a ResultSet.
ResultSet is iterated to print all the employees.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile
and run as follows −
import [Link].*;
// This class demonstrates the way of creating a table which is exactly
similar to another table.
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
String QUERY1 = "CREATE TABLE EMPLOYEES_O LIKE EMPLOYEES";
[Link](QUERY1);
ResultSet rs = [Link]("SELECT * FROM EMPLOYEES");
[Link]("Displaying records from EMPLOYEES_O");
while ([Link]()){
[Link]("Id: " + [Link]("id"));
[Link](" Age: " + [Link]("age"));
[Link](" First: " + [Link]("first"));
[Link](" Last: " + [Link]("last"));
[Link]("------------------------------------------");
}
}catch(SQLException e){
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Displaying records from EMPLOYEES_O
Id: 1 Age: 18 First: Zara Last: Ali
------------------------------------------
Id: 2 Age: 25 First: Mahnaz Last: Fatma
------------------------------------------
Id: 3 Age: 20 First: Zaid Last: Khan
------------------------------------------
Id: 4 Age: 28 First: Sumit Last: Mittal
------------------------------------------
Id: 7 Age: 20 First: Rita Last: Tez
------------------------------------------
Id: 8 Age: 20 First: Sita Last: Singh
------------------------------------------
Id: 21 Age: 35 First: Jeevan Last: Rao
------------------------------------------
Id: 22 Age: 40 First: Aditya Last: Chaube
-----------------------------------------
Id: 25 Age: 35 First: Jeevan Last: Rao
------------------------------------------
Id: 26 Age: 35 First: Aditya Last: Chaube
------------------------------------------
Id: 34 Age: 45 First: Ahmed Last: Ali
------------------------------------------
Id: 35 Age: 50 First: Raksha Last: Agarwal
------------------------------------------
C:\>
Print Page
JDBC - Drop Table
Previous
Next
This chapter provides an examples on how to drop a table, drop table if
exists and truncate table using JDBC application. Before executing the
following example, make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using, is up and running.
NOTE Reformatting JDBC Tutorial This is a serious operation and you have
to make a firm decision before proceeding to delete a table, because
everything you have in your table would be lost.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a queryReformatting JDBC Tutorial Requires using an
object of type Statement for building and submitting an SQL
statement to drop a table in a seleted database.
Clean up the environment Reformatting JDBC Tutorial try with
resources automatically closes the resources.
Example: Dropping a Table
We're required to have DROP privileges in order to run DROP TABLE
command.
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared a
SQL string to drop a table REGISTRATION by calling
[Link]() method.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
){
String sql = "DROP TABLE REGISTRATION";
[Link](sql);
[Link]("Table deleted in given database...");
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Table deleted in given database...
C:\>
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Dropping a Table if Exists
A table can be dropped using following command. If it does not exist, this
command will throw error.
DROP TABLE table_name
If we use a check before dropping a table, it will not throw an error and
drops table only if table exists.
DROP TABLE IF EXISTS table_name
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared a
SQL string to drop a table sampledb1 by calling [Link]()
method.
Once table is dropped, we've printed the status and execute another
query to show all the tables in given database and all remaining tables are
printed.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This file demonstrates use of DROP TABLE IF EXISTS command
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
String QUERY = "DROP TABLE IF EXISTS sampledb1";
[Link](QUERY);
[Link]("Table sampledb1 dropped successfully.");
[Link]("----------------------------------------");
ResultSet rs = [Link]("show tables");
[Link]("List of tables");
[Link]("----------------------------------------");
while([Link]()){
[Link]([Link](1));
}
}catch (SQLException e){
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Table sampledb1 dropped successfully.
----------------------------------------
List of tables
----------------------------------------
consumers
employees
employees_o
jdbc_blob_clob
officers
students
C:\>
Example: Truncate Table
DROP TABLE deletes not only all table data, but also table definitions. On
the other hand, TRUNCATE TABLE deletes only table data (or rows).
TRUNCATE TABLE table_name
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared a
SQL string to query a table sampledb4 by calling
[Link]() method to print all the records. Using result in
a ResultSet, we've printed all the records.
With a new query to truncate the table sampledb4, we've truncated the
table using execute() method. Now again, we're fired the select query to
get all the records. As resultant resultset is empty, a corresponding
message is printed.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
String sel_query = "select * from sampledb4";
ResultSet rs1 = [Link](sel_query);
[Link]("Rows from sampledb4");
[Link]("--------------------");
while([Link]()){
[Link]("id: " + [Link](1));
[Link]("name: " + [Link](2));
}
String QUERY = "TRUNCATE TABLE sampledb4";
[Link](QUERY);
[Link]("Table sampledb4 rows successfully deleted.");
[Link]("----------------------------------------");
[Link](" Doing a select on sampledb4...");
rs1 = [Link](sel_query);
if (![Link]()){
[Link](" **** ResultSet is empty *****");
}
}catch(SQLException e){
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Rows from sampledb4
--------------------
id: 1
name: Gandhi
id: 2
name: marx
Table sampledb4 rows successfully deleted.
----------------------------------------
Doing a select on sampledb4.
**** ResultSet is empty *****
C:\>
JDBC - Insert Records
Previous
Next
This chapter provides examples on how to insert a record, insert multiple
records, insert with select query in a table using JDBC application. Before
executing following example, make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Register the JDBC driver − Requires that you initialize a driver so
you can open a communications channel with the database.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to insert records into a
table.
Clean up the environment try with resources automatically closes
the resources.
Example: Inserting Record in a Table
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared a
SQL string to insert a record into a table REGISTRATION and inserted the
record in database by calling [Link]() method.
Thereafter we've updated the SQL string to insert more new records and
using executeUpdate() method, all records are inserted one by one.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
){
// Execute a query
[Link]("Inserting records into the table...");
String sql = "INSERT INTO Registration VALUES (100, 'Zara', 'Ali',
18)";
[Link](sql);
sql = "INSERT INTO Registration VALUES (101, 'Mahnaz', 'Fatma',
25)";
[Link](sql);
sql = "INSERT INTO Registration VALUES (102, 'Zaid', 'Khan', 30)";
[Link](sql);
sql = "INSERT INTO Registration VALUES(103, 'Sumit', 'Mittal', 28)";
[Link](sql);
[Link]("Inserted records into the table...");
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Inserting records into the table...
Inserted records into the table...
C:\>
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Inserting Record in Single Statement in
a Table
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared a
SQL string to insert multiple records in one go into a table sampledb4 and
inserted the record in database by calling [Link]() method.
Thereafter we've run a select query to read all records from the table and
printed the same.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of multiple inserts within a single SQL
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
[Link]("INSERT INTO sampledb4(id, name) VALUES(3,
'Sachin'), (4, 'Kishore')");
[Link]("----- Successfully inserted into table sampledb4
----\n\n");
[Link]("Displaying records from sampledb4 table,
showing inserted values");
[Link]("---------------------------");
ResultSet rs = [Link]("select * from sampledb4");
while([Link]()){
[Link]("id: " + [Link](1));
[Link]("name: " + [Link](2));
}
}catch(SQLException e){
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
----- Successfully inserted into table sampledb4 ----
Displaying records from sampledb4 table, showing inserted values
---------------------------
id: 3
name: Sachin
id: 4
name: Kishore
C:\>
Example: Inserting Record Using Select
Statement in a Table
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared a
SQL string to insert records using a select query into a table sampledb4
and inserted the record in database by calling [Link]()
method. Thereafter we've run a select query to read all records from the
table and printed the same.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of INSERT..SELECT SQL,
//where data is inserted in table using select from another table.
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
// Data from students table (student id, first name) is inserted into
sampledb4(id, name)
String ins_sel = "insert into sampledb4(id, name) select studentid,"
+" firstname from students where studentid > 1004";
[Link](ins_sel);
ResultSet rs = [Link]("select * from sampledb4 ");
[Link]("Displaying records of table sampledb4/ Ids"
+" greater than 1004 are from students table");
[Link]("--------------------------------------");
while([Link]()){
[Link]("id: " + [Link](1));
[Link](" name: " + [Link](2));
}
}catch(SQLException e){
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying records of table sampledb4/ Ids greater than 1004 are from
students table
--------------------------------------
id: 3 name: Sachin
id: 4 name: Kishore
id: 1005 name: Kishore
id: 1006 name: Ganesh
C:\>
JDBC - Select Records
Previous
Next
This chapter provides examples on how to select/ fetch records from a
table using JDBC application. Before executing the following example,
make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to select (i.e. fetch )
records from a table.
Extract Data − Once SQL query is executed, you can fetch records
from the table.
Clean up the environment − try with resources automatically
closes the resources.
Example: Selecting Record from a Table
In this example, we've four static strings containing a dababase
connection url, username, password and a SELECT query. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've executed a
query on table REGISTRATION by calling [Link]()
method and we've stored the result in ResultSet. ResultSet is iterated and
all records are printed.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM
Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
ResultSet rs = [Link](QUERY);
){
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " + [Link]("first"));
[Link](", Last: " + [Link]("last"));
}
} catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Selecting Records from Multiple Tables
In the last section, we saw how a SELECT works from a single table. Here,
we will see how to do a SELECT from multiple tables using INNER JOIN. The
SELECT Query is:
SELECT [Link], [Link], [Link] from
students INNER JOIN sampledb4 where [Link] =
[Link]
The keyword INNER JOIN is optional. So, the above statement is equivalent
to:
SELECT [Link], [Link], [Link] from
students, sampledb4 where [Link] = [Link]
SampleDb4 table details
In this example, we've four static strings containing a dababase
connection url, username, password and a SELECT query. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've executed a
query on table students and sampledb4 by calling
[Link]() method and we've stored the result in
ResultSet to find students whose id is present in sampledb4 table as well.
ResultSet is iterated and all records are printed.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of INNER JOIN with 2 tables in SQL
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
// Example of INNER JOIN
String query1 = "select [Link], [Link],
[Link]"
+" from students, sampledb4 where [Link] =
[Link]";
ResultSet rs = [Link](query1);
while([Link]()){
[Link](" Student ID: " + [Link](1));
[Link](" FirstName: " + [Link](2));
[Link](" LastName: " + [Link](3));
}
[Link]();
[Link]();
[Link]();
}catch(SQLException e){
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Student ID: 1005 FirstName: Kishore LastName: Kumar
Student ID: 1006 FirstName: Ganesh LastName: Khan
C:\>
Example: Selecting Records from a Table with
Order By
SELECT statement where the results can be ordered by a particular
column in an ascending (using ASC keyword) or descending (using DESC
keyword). Check the sample SQL below:
select id, age, first, last from employees order by age asc;
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've executed a
query on table employees by calling [Link]() method
and we've stored the result in ResultSet. ResultSet is iterated and all
records are printed.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of ORDER BY clause of the SELECT
statement in SQL
public class SelectOrderBy {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
// Example of ORDER BY
String query1 = "select id, age, first, last from employees order by
age asc;";
ResultSet rs = [Link](query1);
while([Link]()){
[Link](" ID: " + [Link](1));
[Link](" AGE: " + [Link](2));
[Link](" FirstName: " + [Link](3));
[Link](" LastName: " + [Link](4));
}
[Link]();
[Link]();
[Link]();
}catch(SQLException e){
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 1 AGE: 18 FirstName: Zara LastName: Ali
ID: 3 AGE: 20 FirstName: Zaid LastName: Khan
ID: 7 AGE: 20 FirstName: Rita LastName: Tez
ID: 8 AGE: 20 FirstName: Sita LastName: Singh
ID: 2 AGE: 25 FirstName: Mahnaz LastName: Fatma
ID: 4 AGE: 28 FirstName: Sumit LastName: Mittal
ID: 21 AGE: 35 FirstName: Jeevan LastName: Rao
ID: 25 AGE: 35 FirstName: Jeevan LastName: Rao
ID: 26 AGE: 35 FirstName: Aditya LastName: Chaube
ID: 22 AGE: 40 FirstName: Aditya LastName: Chaube
ID: 34 AGE: 45 FirstName: Ahmed LastName: Ali
ID: 35 AGE: 50 FirstName: Raksha LastName: Agarwal
C:\>
JDBC - Update Records
Previous
Next
This chapter provides examples on how to update records in a table using
JDBC application. Before executing the following example, make sure you
have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to update records in a
table. This Query makes use of IN and WHERE clause to update
conditional records.
Clean up the environment − try with resources automatically
closes the resources.
Example: Updating Record in a Table Using
Statement Object
In this example, we've four static strings containing a dababase
connection url, username, password and a SELECT query. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed an update query on table REGISTRATION by calling
[Link]() method where we've updated age as 30
where registration id are 100 and 101. Then using executeQuery(), all
records are fetched and stored in a ResultSet object. ResultSet is iterated
and all records are printed.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM
Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
){
String sql = "UPDATE Registration " +
"SET age = 30 WHERE id in (100, 101)";
[Link](sql);
ResultSet rs = [Link](QUERY);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " + [Link]("first"));
[Link](", Last: " + [Link]("last"));
}
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 101, Age: 30, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Updating Record in a Table Using
PreparedStatement
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a
PreparedStatement object using prepareStatement() method. As next
step, We've prepared and executed an update query on table employees
by calling [Link]() method where we've updated age
as 51 where employee id is 35. Then using executeQuery(), updated
record is fetched and stored in a ResultSet object. ResultSet is iterated
and the record is printed.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of UPDATE using Java PreparedStatement
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
String upd_qry = "update employees set age = ? where id =? ";
PreparedStatement pstmt = [Link]( upd_qry);
[Link](1, 51);
[Link](2, 35);
[Link]();
String sel_qry = "select * from employees where id = 35";
ResultSet rs = [Link](sel_qry);
[Link]("Displaying updated record..");
while([Link]()){
[Link](" ID: " + [Link](1));
[Link](" AGE: " + [Link](2));
[Link](" FirstName: " + [Link](3));
[Link](" LastName: " + [Link](4));
}
[Link]();
[Link]();
[Link]();
}catch(SQLException e){
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying updated record..
ID: 35 AGE: 51 FirstName: Raksha LastName: Agarwal
C:\>
Example: Updating Multiple Columns in single
SQL
We can update multiple columns easily as well.
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed an update query on table employees by calling
[Link]() method where we've updated age as 50 and
first name as Shahbaz where employee id is 1. Then using
executeQuery(), updated record is fetched and stored in a ResultSet
object. ResultSet is iterated and the record is printed.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of updating multiple columns with a single
SQL command
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
String upd_qry = "update employees set age = 50, first='Shahbaz'
where id =1 ";
Statement stmt = [Link]();
[Link](upd_qry);
String sel_qry = "select * from employees where id = 1";
ResultSet rs = [Link](sel_qry);
[Link]("Displaying updated record..");
while([Link]()){
[Link](" ID: " + [Link](1));
[Link](", AGE: " + [Link](2));
[Link](", FirstName: " + [Link](3));
[Link](", LastName: " + [Link](4));
}
[Link]();
[Link]();
[Link]();
}catch(SQLException e){
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying updated record..
ID: 1, AGE: 50, FirstName: Shahbaz, LastName: Ali
C:\>
JDBC - Delete Records
Previous
Next
This chapter provides examples on how to delete records from a table
using JDBC application. Before executing following example, make sure
you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Register the JDBC driver − Requires that you initialize a driver so
you can open a communications channel with the database.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to delete records from a
table. This Query makes use of the WHERE clause to delete
conditional records.
Clean up the environment − try with resources automatically
closes the resources.
Example: Deleting Record from a Table
In this example, we've four static strings containing a dababase
connection url, username, password and a SELECT query. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed an update query on table REGISTRATION by calling
[Link]() method where we've deleted a record whose
registration id is 101. Then using executeQuery(), all records are fetched
and stored in a ResultSet object. ResultSet is iterated and all records are
printed.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM
Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
){
String sql = "DELETE FROM Registration " +
"WHERE id = 101";
[Link](sql);
ResultSet rs = [Link](QUERY);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " + [Link]("first"));
[Link](", Last: " + [Link]("last"));
}
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Deleting Records using Limit from a
Table
We can delete limited records using LIMIT clause.
DELETE FROM employees ORDER BY age LIMIT 3
Number of rows deleted is set by the LIMIT clause. In the above SQL, 3
rows will be deleted.
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed a select query on table employees by calling
[Link]() method where we've retrieved all the records
and then using showResults() method, all records are printed.
showResults() method iterates all records of resultset to print them.
Using executeUpdate(), the delete query with Limit clause is executed
and then again using select query on employees table, all records are
printed to show the result of deleting records.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates DELETE command with LIMIT
public class DeleteWithLimit {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
String sel_qry = "select * from employees ";
String del_qry = "DELETE FROM employees ORDER BY age LIMIT 3 ";
Statement stmt = [Link]();
ResultSet rs = [Link](sel_qry);
[Link](" Displaying records before deletion ");
[Link](" ----------------------------------" );
showResults(rs);
[Link](del_qry);
[Link]("Displaying records after deletion..");
[Link](" ----------------------------------" );
rs = [Link](sel_qry);
showResults(rs);
[Link]();
[Link]();
[Link]();
}catch(SQLException e){
[Link]();
}
}
public static void showResults(ResultSet res) {
try{
while([Link]()){
[Link]("ID: " + [Link](1));
[Link](", AGE: " + [Link](2));
[Link](", FirstName: " + [Link](3));
[Link](", LastName: " + [Link](4));
}
[Link](" ----------------------------------" );
}catch(SQLException sqle){
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying records before deletion
----------------------------------
ID: 1, AGE: 50, FirstName: Shahbaz, LastName: Ali
ID: 2, AGE: 25, FirstName: Mahnaz, LastName: Fatma
ID: 3, AGE: 20, FirstName: Zaid, LastName: Khan
ID: 4, AGE: 28, FirstName: Sumit, LastName: Mittal
ID: 7, AGE: 20, FirstName: Rita, LastName: Tez
ID: 8, AGE: 20, FirstName: Sita, LastName: Singh
ID: 21, AGE: 35, FirstName: Jeevan, LastName: Rao
ID: 22, AGE: 40, FirstName: Aditya, LastName: Chaube
ID: 25, AGE: 35, FirstName: Jeevan, LastName: Rao
ID: 26, AGE: 35, FirstName: Aditya, LastName: Chaube
ID: 34, AGE: 45, FirstName: Ahmed, LastName: Ali
ID: 35, AGE: 51, FirstName: Raksha, LastName: Agarwal
----------------------------------
Displaying records after deletion..
----------------------------------
ID: 1, AGE: 50, FirstName: Shahbaz, LastName: Ali
ID: 2, AGE: 25, FirstName: Mahnaz, LastName: Fatma
ID: 4, AGE: 28, FirstName: Sumit, LastName: Mittal
ID: 21, AGE: 35, FirstName: Jeevan, LastName: Rao
ID: 22, AGE: 40, FirstName: Aditya, LastName: Chaube
ID: 25, AGE: 35, FirstName: Jeevan, LastName: Rao
ID: 26, AGE: 35, FirstName: Aditya, LastName: Chaube
ID: 34, AGE: 45, FirstName: Ahmed, LastName: Ali
ID: 35, AGE: 51, FirstName: Raksha, LastName: Agarwal
----------------------------------
C:\>
Example: Deleting Records using JOIN
We will show how deletion from two tables will occur with a JOIN. Before
delete, the tables STUDENTS and SAMPLEDB4 are as follows. Note some
StudentID's (in STUDENTS table) are same as ID's in Sampledb4. The
FirstName is also similar.
In this example, we've three static strings containing a dababase
connection url, username, password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed a delete query on table students and sampledb4 by calling
[Link]() method where we've deleted a student record
whose id is present in sampledb4 table as well. Then using
executeQuery(), all records are fetched and stored in a ResultSet object.
ResultSet is iterated and the records are printed.
In case of any exception while connecting to the database, a catch block
handled SQLException and printed the stack trace.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
String del_qry = "delete sampledb4 from students INNER JOIN"+
" sampledb4 where [Link] = [Link]";
Statement stmt = [Link]();
[Link](del_qry);
[Link]("Displaying records after deletion..");
[Link](" ----------------------------------" );
ResultSet rs = [Link]("select * from sampledb4");
while([Link]()){
[Link]("ID: " + [Link](1));
[Link](", Name: " + [Link](2));
}
[Link]("-----------------------------------");
[Link]();
[Link]();
[Link]();
}catch(SQLException e){
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying records after deletion..
----------------------------------
ID: 3, Name: Sachin
ID: 4, Name: Kishore
JDBC - WHERE Clause
Previous
Next
This chapter provides examples on how to select records from a table
using JDBC application. This would add additional conditions using WHERE
clause while selecting records from the table. Before executing the
following example, make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using, is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for the database programming.
Most often, using import [Link].* will suffice.
Register the JDBC driver − Requires that you initialize a driver so
you can open a communications channel with the database.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to fetch records from a
table, which meet the given condition. This Query makes use of
the WHERE clause to select records.
Clean up the environment − try with resources automatically
closes the resources.
Example: Selecting Records from a Table on
Given Condition
In this example, we've four static strings containing a dababase
connection url, username, password and a SELECT query. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed the SELECT query on table REGISTRATION by calling
[Link]() method. All records are fetched and stored in a
ResultSet object. ResultSet is iterated and all records are printed.
Now another query with WHERE clause is fired in similar fashion. This
query limits the records for only id which are greater than 101. Records
are fetched and printed.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM
Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();) {
[Link]("Fetching records without condition...");
ResultSet rs = [Link](QUERY);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " + [Link]("first"));
[Link](", Last: " + [Link]("last"));
}
// Select all records having ID equal or greater than 101
[Link]("Fetching records with condition...");
String sql = "SELECT id, first, last, age FROM Registration" +
" WHERE id >= 101 ";
rs = [Link](sql);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " + [Link]("first"));
[Link](", Last: " + [Link]("last"));
}
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Fetching records without condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Fetching records with condition...
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Selecting Record from a Table on
Multiple Conditions
In this example, we've three static strings containing a dababase
connection url, username and password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed the SELECT query on table employees by calling
[Link]() method. This query limits the records for ids
which are greater than 1 and employee age being greater than 20.
Records are fetched and printed.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of multiple conditions on WHERE
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
String sel_qry = "select id, first, last from employees where id > 1
and age > 20";
ResultSet rs = [Link](sel_qry);
[Link]("Displaying records depending on the conditions
set in WHERE clause");
[Link]("-------------------------------------------------------");
while([Link]()){
[Link]("id: " + [Link](1));
[Link](", First: " + [Link](2));
[Link](", Last: " + [Link](3));
}
[Link]("--------------------------------------------");
[Link]();
[Link]();
[Link]();
}catch( SQLException e){
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying records depending on the conditions set in WHERE clause
-------------------------------------------------------
id: 2, First: Mahnaz, Last: Fatma
id: 4, First: Sumit, Last: Mittal
id: 21, First: Jeevan, Last: Rao
id: 22, First: Aditya, Last: Chaube
id: 25, First: Jeevan, Last: Rao
id: 26, First: Aditya, Last: Chaube
id: 34, First: Ahmed, Last: Ali
id: 35, First: Raksha, Last: Agarwal
--------------------------------------------
C:\>
Example: Updating Record of a Table based on
Given Condition
In this example, we've three static strings containing a dababase
connection url, username and password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed an UPDATE query on table employees by calling
[Link]() method. This query updates the first name
and last name of the record where id is 22.
Then we executed the SELECT query on table employees by calling
[Link]() method to select a particular record. Result is
stored in a ResultSet object. ResultSet is iterated and record is printed to
show the updated value.
Records are fetched and printed.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of WHERE clause in an UPDATE statement
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
String upd_qry = "update employees set first='Dinesh', last='Kumar'
where id=22";
[Link](upd_qry);
ResultSet rs = [Link]("select id, first, last from
employees where id=22");
[Link]("Displaying records depending on the conditions
set in WHERE clause");
[Link]("-------------------------------------------------------");
while([Link]()){
[Link]("id: " + [Link](1));
[Link](", First: " + [Link](2));
[Link](", Last: " + [Link](3));
}
[Link]("--------------------------------------------");
[Link]();
[Link]();
[Link]();
}catch( SQLException e){
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying records depending on the conditions set in WHERE clause
-------------------------------------------------------
id: 22, First: Dinesh, Last: Kumar
--------------------------------------------
C:\>
JDBC - LIKE Clause
Previous
Next
This chapter provides examples on how to select records from a table
using JDBC application. This would add additional conditions using LIKE
clause while selecting records from the table. Before executing the
following example, make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using, is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to fetch records from a
table which meet given condition. This Query makes use
of LIKE clause to select records to select all the students whose first
name starts with "za".
Clean up the environment − try with resources automatically
closes the resources.
Example: Selecting Record from a Table
In this example, we've four static strings containing a dababase
connection url, username, password and a SELECT query. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed a query on table REGISTRATION by calling
[Link]() method where all records are fetched and
stored in a ResultSet object. ResultSet is iterated and all records are
printed.
As next, we've prepared a SQL query with LIKE clause to get result where
first name is having "za". Query is executed using
[Link]() method where relevant records are fetched
and stored in a ResultSet object. ResultSet is iterated and records are
printed
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM
Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();) {
[Link]("Fetching records without condition...");
ResultSet rs = [Link](QUERY);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " + [Link]("first"));
[Link](", Last: " + [Link]("last"));
}
// Select all records having ID equal or greater than 101
[Link]("Fetching records with condition...");
String sql = "SELECT id, first, last, age FROM Registration" +
" WHERE first LIKE '%za%'";
rs = [Link](sql);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " + [Link]("first"));
[Link](", Last: " + [Link]("last"));
}
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Fetching records without condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Fetching records with condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
C:\>
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Selecting Record from a Table
In this example, we've three static strings containing a dababase
connection url, username and password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed a query on table STUDENTS by calling
[Link]() method where records are fetched where last
name starts with A and stored in a ResultSet object. ResultSet is iterated
and all records are printed.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
String sel_qry = "select studentID, firstName, lastName from
students where lastName like 'A%'";
ResultSet rs = [Link](sel_qry);
[Link]("Displaying records where LastName begins with
'A'" );
[Link]("-------------------------------------------------------");
while([Link]()){
[Link]("studentID: " + [Link](1));
[Link](", FirstName: " + [Link](2));
[Link](", LastName: " + [Link](3));
}
[Link]("--------------------------------------------");
[Link]();
[Link]();
[Link]();
}catch(SQLException e){
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
Output
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying records where LastName begins with 'A'
-------------------------------------------------------
studentID: 1000, FirstName: Bonny, LastName: Agarwal
studentID: 1004, FirstName: Mohammed, LastName: Ali
--------------------------------------------
C:\>
Example: Selecting Record from a Table
In this example, we've three static strings containing a dababase
connection url, username and password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed a query on table EMPLOYEES by calling
[Link]() method where records are fetched where age
begins with 5 and have only one literal after it and stored in a ResultSet
object. ResultSet is iterated and all records are printed.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use of LIKE with underscore '_'
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
String sel_qry = "select * from employees where age like '5_'";
ResultSet rs = [Link](sel_qry);
[Link]("Displaying records where age begins with 5 and
has only one literal after it." );
[Link]("-------------------------------------------------------");
while([Link]()){
[Link](" ID: " + [Link](1));
[Link](", AGE: " + [Link](2));
[Link](", FirstName: " + [Link](3));
[Link](", LastName: " + [Link](4));
}
[Link]("--------------------------------------------");
[Link]();
[Link]();
[Link]();
}catch(SQLException e){
[Link]();
}
}
}
Output
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying records where age begins with 5 and has only one literal after it.
-------------------------------------------------------
ID: 1, AGE: 50, FirstName: Shahbaz, LastName: Ali
ID: 35, AGE: 51, FirstName: Raksha, LastName: Agarwal
--------------------------------------------
C:\>
JDBC - Sorting Data
Previous
Next
This chapter provides an example on how to sort records from a table
using JDBC application. This would use asc and desc keywords to sort
records in ascending or descending order. Before executing the following
example, make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using, is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to sort records from a
table. These Queries make use of asc and desc clauses to sort data
in ascending and descening orders.
Clean up the environment − try with resources automatically
closes the resources.
Example: Sorting Records of a Table
In this example, we've four static strings containing a dababase
connection url, username, password and a SELECT query. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed a SELECT query on table REGISTRATION by calling
[Link]() method where we've added a Order By clause
on first name in Ascending order. Then using executeQuery(), all records
are fetched and stored in a ResultSet object. ResultSet is iterated and all
records are printed.
As next step, We've prepared and executed a SELECT query on table
REGISTRATION by calling [Link]() method where we've
added a Order By clause on first name in Descending order. Then using
executeQuery(), all records are fetched and stored in a ResultSet object.
ResultSet is iterated and all records are printed.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM
Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();) {
[Link]("Fetching records in ascending order...");
ResultSet rs = [Link](QUERY + " ORDER BY first ASC");
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " + [Link]("first"));
[Link](", Last: " + [Link]("last"));
}
[Link]("Fetching records in descending order...");
rs = [Link](QUERY + " ORDER BY first DESC");
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " + [Link]("first"));
[Link](", Last: " + [Link]("last"));
}
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Fetching records in ascending order...
ID: 103, Age: 28, First: Sumit, Last: Mittal
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 100, Age: 30, First: Zara, Last: Ali
Fetching records in descending order...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
Example: Sorting Records of a Table on Two
Columns
In this example, we've three static strings containing a dababase
connection url, username and password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed a SELECT query on table EMPLOYEES by calling
[Link]() method where we've added a Order By clause
on id and age in Ascending order. Then using executeQuery(), all records
are fetched and stored in a ResultSet object. ResultSet is iterated and all
records are printed.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates use ORDER BY with 2 columns.
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
String sel_qry = " select * from employees order by id, age ";
ResultSet rs = [Link](sel_qry);
[Link]("Displaying records from EMPLOYEES table sorted
by id, age" );
[Link]("-------------------------------------------------------");
while([Link]()){
[Link](" ID: " + [Link](1));
[Link](", AGE: " + [Link](2));
[Link](", FirstName: " + [Link](3));
[Link](", LastName: " + [Link](4));
}
[Link]("--------------------------------------------");
[Link]();
[Link]();
[Link]();
}catch(SQLException e){
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying records from EMPLOYEES table sorted by id, age
-------------------------------------------------------
ID: 1, AGE: 50, FirstName: Shahbaz, LastName: Ali
ID: 2, AGE: 25, FirstName: Mahnaz, LastName: Fatma
ID: 4, AGE: 28, FirstName: Sumit, LastName: Mittal
ID: 21, AGE: 35, FirstName: Jeevan, LastName: Rao
ID: 22, AGE: 40, FirstName: Dinesh, LastName: Kumar
ID: 25, AGE: 35, FirstName: Jeevan, LastName: Rao
ID: 26, AGE: 35, FirstName: Aditya, LastName: Chaube
ID: 34, AGE: 45, FirstName: Ahmed, LastName: Ali
ID: 35, AGE: 51, FirstName: Raksha, LastName: Agarwal
--------------------------------------------
C:\>
Example: Sorting Records of a Table in Ascending
as well Descending Order
In this example, we've three static strings containing a dababase
connection url, username and password. Now using
[Link]() method, we've prepared a database
connection. Once connection is prepared, we've prepared a Statement
object using createStatement() method. As next step, We've prepared and
executed a SELECT query on table EMPLOYEES by calling
[Link]() method where we've added a Order By clause
on age as Ascending and last name as in Descending order. Then using
executeQuery(), all records are fetched and stored in a ResultSet object.
ResultSet is iterated and all records are printed.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
// This class demonstrates ORDER BY 2 columns one ASC, one DESC
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "root";
static final String PASS = "guest123";
public static void main(String args[]) {
try{
Connection conn = [Link](DB_URL, USER,
PASS);
Statement stmt = [Link]();
String sel_qry = " select * from employees order by age asc, last
desc";
ResultSet rs = [Link](sel_qry);
[Link]("Displaying records from EMPLOYEES table sorted
by age(ASC) and last name (DESC)." );
[Link]("-------------------------------------------------------");
while([Link]()){
[Link](" ID: " + [Link](1));
[Link](", AGE: " + [Link](2));
[Link](", FirstName: " + [Link](3));
[Link](", LastName: " + [Link](4));
}
[Link]("--------------------------------------------");
[Link]();
[Link]();
[Link]();
}catch(SQLException e){
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Displaying records from EMPLOYEES table sorted by age(ASC) and last name
(DESC).
-------------------------------------------------------
ID: 2, AGE: 25, FirstName: Mahnaz, LastName: Fatma
ID: 4, AGE: 28, FirstName: Sumit, LastName: Mittal
ID: 21, AGE: 35, FirstName: Jeevan, LastName: Rao
ID: 25, AGE: 35, FirstName: Jeevan, LastName: Rao
ID: 26, AGE: 35, FirstName: Aditya, LastName: Chaube
ID: 22, AGE: 40, FirstName: Dinesh, LastName: Kumar
ID: 34, AGE: 45, FirstName: Ahmed, LastName: Ali
ID: 1, AGE: 50, FirstName: Shahbaz, LastName: Ali
ID: 35, AGE: 51, FirstName: Raksha, LastName: Agarwal
--------------------------------------------
C:\>
JDBC - Questions Answers
Previous
Next
JDBC Questions and Answers has been designed with a special
intention of helping students and professionals preparing for
various Certification Exams and Job Interviews. This section provides
a useful collection of sample Interview Questions and Multiple Choice
Questions (MCQs) and their answers with appropriate explanations.
S
Question/Answers Type
N
JDBC Interview Questions
1
This section provides a huge collection of JDBC Interview Questions with their answers hidden in a box
at them before discovering the correct answer.
JDBC Online Quiz
2
This section provides a great collection of JDBC Multiple Choice Questions (MCQs) on a single
answers and explanation. If you select the right option, it turns green; else red.
JDBC Online Test
3 If you are preparing to appear for a Java and JDBC Framework related certification exam, then this s
section simulates a real online test along with a given timer which challenges you to complete the te
Finally you can check your overall test score and how you fared among millions of other candidates who
JDBC Mock Test
4
This section provides various mock tests that you can download at your local machine and solve offlin
with a mock test key to let you verify the final score and grade yourself.
JDBC - Quick Guide
Previous
Next
JDBC - Introduction
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API
for database-independent connectivity between the Java programming
language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned below that
are commonly associated with database usage.
Making a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the database.
Viewing & Modifying the resulting records.
Fundamentally, JDBC is a specification that provides a complete set of
interfaces that allows for portable access to an underlying database. Java
can be used to write different types of executables, such as −
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a
database, and take advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to
contain database-independent code.
Pre-Requisite
Before moving further, you need to have a good understanding of the
following two subjects −
Core JAVA Programming
SQL or MySQL Database
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for
database access but in general, JDBC Architecture consists of two layers −
JDBC API − This provides the application-to-JDBC Manager
connection.
JDBC Driver API − This supports the JDBC Manager-to-Driver
Connection.
The JDBC API uses a driver manager and database-specific drivers to
provide transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access
each data source. The driver manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the
driver manager with respect to the JDBC drivers and the Java application
−
Common JDBC Components
The JDBC API provides the following interfaces and classes −
DriverManager − This class manages a list of database drivers.
Matches connection requests from the java application with the
proper database driver using communication sub protocol. The first
driver that recognizes a certain subprotocol under JDBC will be used
to establish a database Connection.
Driver − This interface handles the communications with the
database server. You will interact directly with Driver objects very
rarely. Instead, you use DriverManager objects, which manages
objects of this type. It also abstracts the details associated with
working with Driver objects.
Connection − This interface with all methods for contacting a
database. The connection object represents communication context,
i.e., all communication with database is through connection object
only.
Statement − You use objects created from this interface to submit
the SQL statements to the database. Some derived interfaces
accept parameters in addition to executing stored procedures.
ResultSet − These objects hold data retrieved from a database
after you execute an SQL query using Statement objects. It acts as
an iterator to allow you to move through its data.
SQLException − This class handles any errors that occur in a
database application.
The JDBC 4.0 Packages
The [Link] and [Link] are the primary packages for JDBC 4.0. This is
the latest JDBC version at the time of writing this tutorial. It offers the
main classes for interacting with your data sources.
The new features in these packages include changes in the following
areas −
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.
JDBC - SQL Syntax
Structured Query Language (SQL) is a standardized language that allows
you to perform operations on a database, such as creating entries,
reading content, updating content, and deleting entries.
SQL is supported by almost any database you will likely use, and it allows
you to write database code independently of the underlying database.
This chapter gives an overview of SQL, which is a prerequisite to
understand JDBC concepts. After going through this chapter, you will be
able to Create, Create, Read, Update, and Delete (often referred to
as CRUD operations) data from a database.
For a detailed understanding on SQL, you can read our MySQL Tutorial.
Create Database
The CREATE DATABASE statement is used for creating a new database.
The syntax is −
SQL> CREATE DATABASE DATABASE_NAME;
Example
The following SQL statement creates a Database named EMP −
SQL> CREATE DATABASE EMP;
Drop Database
The DROP DATABASE statement is used for deleting an existing database.
The syntax is −
SQL> DROP DATABASE DATABASE_NAME;
Note − To create or drop a database you should have administrator
privilege on your database server. Be careful, deleting a database would
loss all the data stored in the database.
Create Table
The CREATE TABLE statement is used for creating a new table. The syntax
is −
SQL> CREATE TABLE table_name
(
column_name column_data_type,
column_name column_data_type,
column_name column_data_type
...
);
Example
The following SQL statement creates a table named Employees with four
columns −
SQL> CREATE TABLE Employees
(
id INT NOT NULL,
age INT NOT NULL,
first VARCHAR(255),
last VARCHAR(255),
PRIMARY KEY ( id )
);
Drop Table
The DROP TABLE statement is used for deleting an existing table. The
syntax is −
SQL> DROP TABLE table_name;
Example
The following SQL statement deletes a table named Employees −
SQL> DROP TABLE Employees;
INSERT Data
The syntax for INSERT, looks similar to the following, where column1,
column2, and so on represents the new data to appear in the respective
columns −
SQL> INSERT INTO table_name VALUES (column1, column2, ...);
Example
The following SQL INSERT statement inserts a new row in the Employees
database created earlier −
SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
SELECT Data
The SELECT statement is used to retrieve data from a database. The
syntax for SELECT is −
SQL> SELECT column_name, column_name, ...
FROM table_name
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >,
<=,and >=, as well as the BETWEEN and LIKE operators.
Example
The following SQL statement selects the age, first and last columns from
the Employees table, where id column is 100 −
SQL> SELECT first, last, age
FROM Employees
WHERE id = 100;
The following SQL statement selects the age, first and last columns from
the Employees table where first column contains Zara −
SQL> SELECT first, last, age
FROM Employees
WHERE first LIKE '%Zara%';
UPDATE Data
The UPDATE statement is used to update data. The syntax for UPDATE is
−
SQL> UPDATE table_name
SET column_name = value, column_name = value, ...
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >,
<=,and >=, as well as the BETWEEN and LIKE operators.
Example
The following SQL UPDATE statement changes the age column of the
employee whose id is 100 −
SQL> UPDATE Employees SET age=20 WHERE id=100;
DELETE Data
The DELETE statement is used to delete data from tables. The syntax for
DELETE is −
SQL> DELETE FROM table_name WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <, >,
<=,and >=, as well as the BETWEEN and LIKE operators.
Example
The following SQL DELETE statement deletes the record of the employee
whose id is 100 −
SQL> DELETE FROM Employees WHERE id=100;
JDBC - Environment
To start developing with JDBC, you should setup your JDBC environment
by following the steps shown below. We assume that you are working on a
Windows platform.
Install Java
Java SE is available for download for free. To download click here, please
download a version compatible with your operating system.
Follow the instructions to download Java, and run the .exe to install Java
on your machine. Once you have installed Java on your machine, you
would need to set environment variables to point to correct installation
directories.
Setting Up the Path for Windows 2000/XP
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced'
tab.
Now, edit the 'Path' variable and add the path to the Java
executable directory at the end of it. For example, if the path is
currently set to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin
Setting Up the Path for Windows 95/98/ME
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Edit the 'C:\[Link]' file and add the following line at the end −
SET PATH = %PATH%;C:\Program Files\java\jdk\bin
Setting Up the Path for Linux, UNIX, Solaris, FreeBSD
Environment variable PATH should be set to point to where the Java
binaries have been installed. Refer to your shell documentation if you
have trouble doing this.
For example, if you use bash as your shell, then you would add the
following line at the end of your .bashrc −
export PATH = /path/to/java:$PATH'
You automatically get both JDBC packages [Link] and [Link], when
you install J2SE Development Kit.
Install Database
The most important thing you will need, of course is an actual running
database with a table that you can query and modify.
Install a database that is most suitable for you. You can have plenty of
choices and most common are −
MySQL DB − MySQL is an open source database. You can download
it from MySQL Official Site. We recommend downloading the full
Windows installation.
In addition, download and install MySQL Administrator as well
as MySQL Query Browser. These are GUI based tools that will make
your development much easier.
Finally, download and unzip MySQL Connector/J (the MySQL JDBC
driver) in a convenient directory. For the purpose of this tutorial we
will assume that you have installed the driver at C:\Program Files\
MySQL\mysql-connector-java-5.1.8.
Accordingly, set CLASSPATH variable to C:\Program Files\MySQL\
mysql-connector-java-5.1.8\[Link]. Your
driver version may vary based on your installation.
Set Database Credential
When we install MySQL database, its administrator ID is set to root and it
gives provision to set a password of your choice.
Using root ID and password you can either create another user ID and
password, or you can use root ID and password for your JDBC application.
There are various database operations like database creation and
deletion, which would need administrator ID and password.
For rest of the JDBC tutorial, we would use MySQL Database with guest as
ID and guest123 as password.
If you do not have sufficient privilege to create new users, then you can
ask your Database Administrator (DBA) to create a user ID and password
for you.
Create Database
To create the TUTORIALSPOINT database, use the following steps −
Step 1
Open a Command Prompt and change to the installation directory as
follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Note − The path to [Link] may vary depending on the install
location of MySQL on your system. You can also check documentation on
how to start and stop your database server.
Step 2
Start the database server by executing the following command, if it is
already not running.
C:\Program Files\MySQL\bin>mysqld
C:\Program Files\MySQL\bin>
Step 3
Create the TUTORIALSPOINT database by executing the following
command −
C:\Program Files\MySQL\bin> mysqladmin create TUTORIALSPOINT -
u guest -p
Enter password: ********
C:\Program Files\MySQL\bin>
Create Table
To create the Employees table in TUTORIALSPOINT database, use the
following steps −
Step 1
Open a Command Prompt and change to the installation directory as
follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2
Login to the database as follows −
C:\Program Files\MySQL\bin>mysql -u guest -p
Enter password: ********
mysql>
Step 3
Create the table Employees as follows −
mysql> use TUTORIALSPOINT;
mysql> create table Employees
-> (
-> id int not null,
-> age int not null,
-> first varchar (255),
-> last varchar (255)
-> );
Query OK, 0 rows affected (0.08 sec)
mysql>
Create Data Records
Finally you create few records in Employee table as follows −
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)
mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz',
'Fatma');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit',
'Mittal');
Query OK, 1 row affected (0.00 sec)
mysql>
For a complete understanding on MySQL database, study the MySQL
Tutorial.
Now you are ready to start experimenting with JDBC. Next chapter gives
you a sample example on JDBC Programming.
JDBC - Sample Code
This chapter provides an example of how to create a simple JDBC
application. This will show you how to open a database connection,
execute a SQL query, and display the results.
All the steps mentioned in this template example, would be explained in
subsequent chapters of this tutorial.
Creating JDBC Application
There are following six steps involved in building a JDBC application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with the database.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to the database.
Extract data from result set − Requires that you use the
appropriate [Link]() method to retrieve the data from
the result set.
Clean up the environment − Requires explicitly closing all
database resources versus relying on the JVM's garbage collection.
Sample Code
This sample example can serve as a template when you need to create
your own JDBC application in the future.
This sample code has been written based on the environment and
database setup done in the previous chapter.
Copy and paste the following example in [Link], compile and
run as follows −
import [Link].*;
public class FirstExample {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age
FROM Employees";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
ResultSet rs = [Link](QUERY);) {
// Extract data from result set
while ([Link]()) {
// Retrieve by column name
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " +
[Link]("first"));
[Link](", Last: " +
[Link]("last"));
}
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run FirstExample, it produces the following result −
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
JDBC - Driver Types
What is JDBC Driver?
JDBC drivers implement the defined interfaces in the JDBC API, for
interacting with your database server.
For example, using JDBC drivers enable you to open database connections
and to interact with it by sending SQL or database commands then
receiving results with Java.
The [Link] package that ships with JDK, contains various classes with
their behaviours defined and their actual implementaions are done in
third-party drivers. Third party vendors implements
the [Link] interface in their database driver.
JDBC Drivers Types
JDBC driver implementations vary because of the wide variety of
operating systems and hardware platforms in which Java operates. Sun
has divided the implementation types into four categories, Types 1, 2, 3,
and 4, which is explained below −
Type 1 − JDBC-ODBC Bridge Driver
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed
on each client machine. Using ODBC, requires configuring on your system
a Data Source Name (DSN) that represents the target database.
When Java first came out, this was a useful driver because most
databases only supported ODBC access but now this type of driver is
recommended only for experimental use or when no other alternative is
available.
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this
kind of driver.
Type 2 − JDBC-Native API
In a Type 2 driver, JDBC API calls are converted into native C/C++ API
calls, which are unique to the database. These drivers are typically
provided by the database vendors and used in the same manner as the
JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.
If we change the Database, we have to change the native API, as it is
specific to a database and they are mostly obsolete now, but you may
realize some speed increase with a Type 2 driver, because it eliminates
ODBC's overhead.
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Type 3 − JDBC-Net pure Java
In a Type 3 driver, a three-tier approach is used to access databases. The
JDBC clients use standard network sockets to communicate with a
middleware application server. The socket information is then translated
by the middleware application server into the call format required by the
DBMS, and forwarded to the database server.
This kind of driver is extremely flexible, since it requires no code installed
on the client and a single driver can actually provide access to multiple
databases.
You can think of the application server as a JDBC "proxy," meaning that it
makes calls for the client application. As a result, you need some
knowledge of the application server's configuration in order to effectively
use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate
with the database, understanding the nuances will prove helpful.
Type 4 − 100% Pure Java
In a Type 4 driver, a pure Java-based driver communicates directly with
the vendor's database through socket connection. This is the highest
performance driver available for the database and is usually provided by
the vendor itself.
This kind of driver is extremely flexible, you don't need to install special
software on the client or server. Further, these drivers can be downloaded
dynamically.
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary
nature of their network protocols, database vendors usually supply type 4
drivers.
Which Driver should be Used?
If you are accessing one type of database, such as Oracle, Sybase, or IBM,
the preferred driver type is 4.
If your Java application is accessing multiple types of databases at the
same time, type 3 is the preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is
not available yet for your database.
The type 1 driver is not considered a deployment-level driver, and is
typically used for development and testing purposes only.
JDBC - Connections
After you've installed the appropriate driver, it is time to establish a
database connection using JDBC.
The programming involved to establish a JDBC connection is fairly simple.
Here are these simple four steps −
Import JDBC Packages − Add import statements to your Java
program to import required classes in your Java code.
Register JDBC Driver − This step causes the JVM to load the
desired driver implementation into memory so it can fulfill your JDBC
requests.
Database URL Formulation − This is to create a properly
formatted address that points to the database to which you wish to
connect.
Create Connection Object − Finally, code a call to
the DriverManager object's getConnection( ) method to establish
actual database connection.
Import JDBC Packages
The Import statements tell the Java compiler where to find the classes
you reference in your code and are placed at the very beginning of your
source code.
To use the standard JDBC package, which allows you to select, insert,
update, and delete data in SQL tables, add the following imports to your
source code −
import [Link].* ; // for standard JDBC programs
import [Link].* ; // for BigDecimal and BigInteger support
Register JDBC Driver
You must register the driver in your program before you use it.
Registering the driver is the process by which the Oracle driver's class file
is loaded into the memory, so it can be utilized as an implementation of
the JDBC interfaces.
You need to do this registration only once in your program. You can
register a driver in one of two ways.
Approach I - [Link]()
The most common approach to register a driver is to use
Java's [Link]() method, to dynamically load the driver's class file
into memory, which automatically registers it. This method is preferable
because it allows you to make the driver registration configurable and
portable.
The following example uses [Link]( ) to register the Oracle driver
−
try {
[Link]("[Link]");
}
catch(ClassNotFoundException ex) {
[Link]("Error: unable to load driver class!");
[Link](1);
}
You can use getInstance() method to work around noncompliant JVMs,
but then you'll have to code for two extra Exceptions as follows −
try {
[Link]("[Link]").newInstanc
e();
}
catch(ClassNotFoundException ex) {
[Link]("Error: unable to load driver class!");
[Link](1);
catch(IllegalAccessException ex) {
[Link]("Error: access problem while loading!");
[Link](2);
catch(InstantiationException ex) {
[Link]("Error: unable to instantiate driver!");
[Link](3);
}
Approach II - [Link]()
The second approach you can use to register a driver, is to use the
static [Link]() method.
You should use the registerDriver() method if you are using a non-JDK
compliant JVM, such as the one provided by Microsoft.
The following example uses registerDriver() to register the Oracle driver −
try {
Driver myDriver = new [Link]();
[Link]( myDriver );
}
catch(ClassNotFoundException ex) {
[Link]("Error: unable to load driver class!");
[Link](1);
}
Database URL Formulation
After you've loaded the driver, you can establish a connection using
the [Link]() method. For easy reference, let
me list the three overloaded [Link]() methods −
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address
that points to your database.
Formulating a database URL is where most of the problems associated
with establishing a connection occurs.
Following table lists down the popular JDBC driver names and database URL.
RDBMS JDBC driver name URL format
MySQL [Link] jdbc:mysql://hostname/ databaseName
ORACLE [Link] jdbc:oracle:thin:@hostname:port Num
DB2 [Link].DB2Driver jdbc:db2:hostname:port Number/database
Sybase [Link] jdbc:sybase:Tds:hostname: port Numb
All the highlighted part in URL format is static and you need to change
only the remaining part as per your database setup.
Create Connection Object
We have listed down three forms
of [Link]() method to create a connection
object.
Using a Database URL with a username and
password
The most commonly used form of getConnection() requires you to pass a
database URL, a username, and a password −
Assuming you are using Oracle's thin driver, you'll specify a
host:port:databaseName value for the database portion of the URL.
If you have a host at TCP/IP address [Link] with a host name of
amrood, and your Oracle listener is configured to listen on port 1521, and
your database name is EMP, then complete database URL would be −
jdbc:oracle:thin:@amrood:1521:EMP
Now you have to call getConnection() method with appropriate username
and password to get a Connection object as follows −
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = [Link](URL, USER,
PASS);
Using Only a Database URL
A second form of the [Link]( ) method requires
only a database URL −
[Link](String url);
However, in this case, the database URL includes the username and
password and has the following general form −
jdbc:oracle:driver:username/password@database
So, the above connection can be created as follows −
String URL =
"jdbc:oracle:thin:username/password@amrood:1521:EMP";
Connection conn = [Link](URL);
Using a Database URL and a Properties Object
A third form of the [Link]( ) method requires a
database URL and a Properties object −
[Link](String url, Properties info);
A Properties object holds a set of keyword-value pairs. It is used to pass
driver properties to the driver during a call to the getConnection()
method.
To make the same connection made by the previous examples, use the
following code −
import [Link].*;
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
Properties info = new Properties( );
[Link]( "user", "username" );
[Link]( "password", "password" );
Connection conn = [Link](URL, info);
Closing JDBC Connections
At the end of your JDBC program, it is required explicitly to close all the
connections to the database to end each database session. However, if
you forget, Java's garbage collector will close the connection when it
cleans up stale objects.
Relying on the garbage collection, especially in database programming, is
a very poor programming practice. You should make a habit of always
closing the connection with the close() method associated with connection
object.
To ensure that a connection is closed, you could provide a 'finally' block in
your code. A finally block always executes, regardless of an exception
occurs or not.
To close the above opened connection, you should call close() method as
follows −
[Link]();
Explicitly closing a connection conserves DBMS resources, which will make
your database administrator happy.
For a better understanding, we suggest you to study our JDBC - Sample
Code tutorial.
JDBC - Statements
Once a connection is obtained we can interact with the database. The
JDBC Statement, CallableStatement, and PreparedStatement interfaces
define the methods and properties that enable you to send SQL or PL/SQL
commands and receive data from your database.
They also define methods that help bridge data type differences between
Java and SQL data types used in a database.
The following table provides a summary of each interface's purpose to decide on the interface to
use.
Interfaces Recommended Use
Use this for general-purpose access to your database. Useful when you are u
Statement
runtime. The Statement interface cannot accept parameters.
Use this when you plan to use the SQL statements many times. The Prepar
PreparedStatement
input parameters at runtime.
Use this when you want to access the database stored procedures. The Callab
CallableStatement
accept runtime input parameters.
The Statement Objects
Creating Statement Object
Before you can use a Statement object to execute a SQL statement, you
need to create one using the Connection object's createStatement( )
method, as in the following example −
Statement stmt = null;
try {
stmt = [Link]( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
Once you've created a Statement object, you can then use it to execute
an SQL statement with one of its three execute methods.
boolean execute (String SQL): Returns a boolean value of true if
a ResultSet object can be retrieved; otherwise, it returns false. Use
this method to execute SQL DDL statements or when you need to
use truly dynamic SQL.
int executeUpdate (String SQL) − Returns the number of rows
affected by the execution of the SQL statement. Use this method to
execute SQL statements for which you expect to get a number of
rows affected - for example, an INSERT, UPDATE, or DELETE
statement.
ResultSet executeQuery (String SQL) − Returns a ResultSet
object. Use this method when you expect to get a result set, as you
would with a SELECT statement.
Closing Statement Object
Just as you close a Connection object to save database resources, for the
same reason you should also close the Statement object.
A simple call to the close() method will do the job. If you close the
Connection object first, it will close the Statement object as well. However,
you should always explicitly close the Statement object to ensure proper
cleanup.
Statement stmt = null;
try {
stmt = [Link]( );
. . .
}
catch (SQLException e) {
. . .
}
finally {
[Link]();
}
For a better understanding, we suggest you to study the Statement -
Example tutorial.
The PreparedStatement Objects
The PreparedStatement interface extends the Statement interface, which
gives you added functionality with a couple of advantages over a generic
Statement object.
This statement gives you the flexibility of supplying arguments
dynamically.
Creating PreparedStatement Object
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = [Link](SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
All parameters in JDBC are represented by the ? symbol, which is known
as the parameter marker. You must supply values for every parameter
before executing the SQL statement.
The setXXX() methods bind values to the parameters,
where XXX represents the Java data type of the value you wish to bind to
the input parameter. If you forget to supply the values, you will receive an
SQLException.
Each parameter marker is referred by its ordinal position. The first marker
represents position 1, the next position 2, and so forth. This method
differs from that of Java array indices, which starts at 0.
All of the Statement object's methods for interacting with the database
(a) execute(), (b) executeQuery(), and (c) executeUpdate() also work with
the PreparedStatement object. However, the methods are modified to use
SQL statements that can input the parameters.
Closing PreparedStatement Object
Just as you close a Statement object, for the same reason you should also
close the PreparedStatement object.
A simple call to the close() method will do the job. If you close the
Connection object first, it will close the PreparedStatement object as well.
However, you should always explicitly close the PreparedStatement object
to ensure proper cleanup.
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = [Link](SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
[Link]();
}
For a better understanding, let us study Prepare - Example Code.
The CallableStatement Objects
Just as a Connection object creates the Statement and PreparedStatement
objects, it also creates the CallableStatement object, which would be used
to execute a call to a database stored procedure.
Creating CallableStatement Object
Suppose, you need to execute the following Oracle stored procedure −
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;
NOTE − Above stored procedure has been written for Oracle, but we are
working with MySQL database so, let us write same stored procedure for
MySQL as follows to create it in EMP database −
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
Three types of parameters exist: IN, OUT, and INOUT. The
PreparedStatement object only uses the IN parameter. The
CallableStatement object can use all the three.
Here are the definitions of each −
Parameter Description
A parameter whose value is unknown when the SQL statement is crea
IN
parameters with the setXXX() methods.
A parameter whose value is supplied by the SQL statement it returns. You
OUT
parameters with the getXXX() methods.
A parameter that provides both input and output values. You bind variables w
INOUT
retrieve values with the getXXX() methods.
The following code snippet shows how to employ
the [Link]() method to instantiate
a CallableStatement object based on the preceding stored procedure −
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = [Link] (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
The String variable SQL, represents the stored procedure, with parameter
placeholders.
Using the CallableStatement objects is much like using the
PreparedStatement objects. You must bind values to all the parameters
before executing the statement, or you will receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that
apply to a PreparedStatement object; use the setXXX() method that
corresponds to the Java data type you are binding.
When you use OUT and INOUT parameters you must employ an additional
CallableStatement method, registerOutParameter(). The
registerOutParameter() method binds the JDBC data type, to the data type
that the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT
parameter with the appropriate getXXX() method. This method casts the
retrieved value of SQL type to a Java data type.
Closing CallableStatement Object
Just as you close other Statement object, for the same reason you should
also close the CallableStatement object.
A simple call to the close() method will do the job. If you close the
Connection object first, it will close the CallableStatement object as well.
However, you should always explicitly close the CallableStatement object
to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = [Link] (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
[Link]();
}
For a better understanding, I would suggest to study Callable - Example
Code.
JDBC - Result Sets
The SQL statements that read data from a database query, return the
data in a result set. The SELECT statement is the standard way to select
rows from a database and view them in a result set.
The [Link] interface represents the result set of a database
query.
A ResultSet object maintains a cursor that points to the current row in the
result set. The term "result set" refers to the row and column data
contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three
categories −
Navigational methods − Used to move the cursor around.
Get methods − Used to view the data in the columns of the current
row being pointed by the cursor.
Update methods − Used to update the data in the columns of the
current row. The updates can then be updated in the underlying
database as well.
The cursor is movable based on the properties of the ResultSet. These
properties are designated when the corresponding Statement that
generates the ResultSet is created.
JDBC provides the following connection methods to create statements
with desired ResultSet −
createStatement(int RSType, int RSConcurrency);
prepareStatement(String SQL, int RSType, int
RSConcurrency);
prepareCall(String sql, int RSType, int RSConcurrency);
The first argument indicates the type of a ResultSet object and the second
argument is one of two ResultSet constants for specifying whether a result
set is read-only or updatable.
Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you will automatically
get one that is TYPE_FORWARD_ONLY.
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
The cursor can scroll forward and backward, and the
ResultSet.TYPE_SCROLL_INSENSITIVE
changes made by others to the database that occur after t
The cursor can scroll forward and backward, and the re
ResultSet.TYPE_SCROLL_SENSITIVE.
made by others to the database that occur after the result
Concurrency of ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type, you will
automatically get one that is CONCUR_READ_ONLY.
Concurrency Description
ResultSet.CONCUR_READ_ONLY Creates a read-only result set. This is the default
ResultSet.CONCUR_UPDATABLE Creates an updateable result set.
All our examples written so far can be written as follows, which initializes
a Statement object to create a forward-only, read only ResultSet object −
try {
Statement stmt = [Link](
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) {
....
}
finally {
....
}
Navigating a Result Set
There are several methods in the ResultSet interface that involve moving the cursor, including −
S.
Methods & Description
N.
public void beforeFirst() throws SQLException
1
Moves the cursor just before the first row.
public void afterLast() throws SQLException
2
Moves the cursor just after the last row.
public boolean first() throws SQLException
3
Moves the cursor to the first row.
public void last() throws SQLException
4
Moves the cursor to the last row.
public boolean absolute(int row) throws SQLException
5
Moves the cursor to the specified row.
public boolean relative(int row) throws SQLException
6
Moves the cursor the given number of rows forward or backward, from where it is currently pointing.
public boolean previous() throws SQLException
7
Moves the cursor to the previous row. This method returns false if the previous row is off the result set
public boolean next() throws SQLException
8
Moves the cursor to the next row. This method returns false if there are no more rows in the result set.
public int getRow() throws SQLException
9
Returns the row number that the cursor is pointing to.
public void moveToInsertRow() throws SQLException
10 Moves the cursor to a special row in the result set that can be used to insert a new row into the databas
is remembered.
public void moveToCurrentRow() throws SQLException
11
Moves the cursor back to the current row if the cursor is currently at the insert row; otherwise, this met
For a better understanding, let us study Navigate - Example Code.
Viewing a Result Set
The ResultSet interface contains dozens of methods for getting the data of
the current row.
There is a get method for each of the possible data types, and each get
method has two versions −
One that takes in a column name.
One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one of the
getInt() methods of ResultSet −
S.
Methods & Description
N.
public int getInt(String columnName) throws SQLException
1
Returns the int in the current row in the column named columnName.
public int getInt(int columnIndex) throws SQLException
2 Returns the int in the current row in the specified column index. The column index starts at 1, meaning
the second column of a row is 2, and so on.
Similarly, there are get methods in the ResultSet interface for each of the
eight Java primitive types, as well as common types such as
[Link], [Link], and [Link].
There are also methods for getting SQL data types [Link],
[Link], [Link], [Link], and [Link]. Check
the documentation for more information about using these SQL data
types.
For a better understanding, let us study Viewing - Example Code.
Updating a Result Set
The ResultSet interface contains a collection of update methods for
updating the data of a result set.
As with the get methods, there are two update methods for each data
type −
One that takes in a column name.
One that takes in a column index.
For example, to update a String column of the current row of a result set, you would use one of the
following updateString() methods −
S.N. Methods & Description
public void updateString(int columnIndex, String s) throws SQLExceptio
1
Changes the String in the specified column to the value of s.
public void updateString(String columnName, String s) throws SQLExce
2
Similar to the previous method, except that the column is specified by its name instead of its index.
There are update methods for the eight primitive data types, as well as
String, Object, URL, and the SQL data types in the [Link] package.
Updating a row in the result set changes the columns of the current row in the ResultSet object, but
not in the underlying database. To update your changes to the row in the database, you need to
invoke one of the following methods.
S.N. Methods & Description
1 public void updateRow()
Updates the current row by updating the corresponding row in the database.
public void deleteRow()
2
Deletes the current row from the database
public void refreshRow()
3
Refreshes the data in the result set to reflect any recent changes in the database.
public void cancelRowUpdates()
4
Cancels any updates made on the current row.
public void insertRow()
5
Inserts a row into the database. This method can only be invoked when the cursor is pointing to the in
For a better understanding, let us study the Updating - Example Code .
JDBC - Data Types
The JDBC driver converts the Java data type to the appropriate JDBC type,
before sending it to the database. It uses a default mapping for most data
types. For example, a Java int is converted to an SQL INTEGER. Default
mappings were created to provide consistency between drivers.
The following table summarizes the default JDBC data type that the Java data type is converted to,
when you call the setXXX() method of the PreparedStatement or CallableStatement object or the
[Link]() method.
SQL JDBC/Java setXXX up
VARCHAR [Link] setString up
CHAR [Link] setString up
LONGVARCHAR [Link] setString up
BIT boolean setBoolean up
NUMERIC [Link] setBigDecimal up
TINYINT byte setByte up
SMALLINT short setShort up
INTEGER int setInt up
BIGINT long setLong up
REAL float setFloat up
FLOAT float setFloat up
DOUBLE double setDouble up
VARBINARY byte[ ] setBytes up
BINARY byte[ ] setBytes up
DATE [Link] setDate up
TIME [Link] setTime up
TIMESTAMP [Link] setTimestamp up
CLOB [Link] setClob up
BLOB [Link] setBlob up
ARRAY [Link] setARRAY up
REF [Link] SetRef up
STRUCT [Link] SetStruct up
JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data
types. The ResultSet object now has updateBLOB(), updateCLOB(),
updateArray(), and updateRef() methods that enable you to directly
manipulate the respective data on the server.
The setXXX() and updateXXX() methods enable you to convert specific
Java types to specific JDBC data types. The methods, setObject() and
updateObject(), enable you to map almost any Java type to a JDBC data
type.
ResultSet object provides corresponding getXXX() method for each data type to retrieve column
value. Each method can be used with column name or by its ordinal position.
SQL JDBC/Java setXXX ge
VARCHAR [Link] setString ge
CHAR [Link] setString ge
LONGVARCHAR [Link] setString ge
BIT boolean setBoolean ge
NUMERIC [Link] setBigDecimal ge
TINYINT byte setByte ge
SMALLINT short setShort ge
INTEGER int setInt ge
BIGINT long setLong ge
REAL float setFloat ge
FLOAT float setFloat ge
DOUBLE double setDouble ge
VARBINARY byte[ ] setBytes ge
BINARY byte[ ] setBytes ge
DATE [Link] setDate ge
TIME [Link] setTime ge
TIMESTAMP [Link] setTimestamp ge
CLOB [Link] setClob ge
BLOB [Link] setBlob ge
ARRAY [Link] setARRAY ge
REF [Link] SetRef ge
STRUCT [Link] SetStruct ge
Date & Time Data Types
The [Link] class maps to the SQL DATE type, and the [Link]
and [Link] classes map to the SQL TIME and SQL TIMESTAMP
data types, respectively.
Following example shows how the Date and Time classes format the
standard Java date and time values to match the SQL data type
requirements.
import [Link];
import [Link];
import [Link];
import [Link].*;
public class SqlDateTime {
public static void main(String[] args) {
//Get standard date and time
[Link] javaDate = new [Link]();
long javaTime = [Link]();
[Link]("The Java Date is:" +
[Link]());
//Get and display SQL DATE
[Link] sqlDate = new [Link](javaTime);
[Link]("The SQL DATE is: " +
[Link]());
//Get and display SQL TIME
[Link] sqlTime = new [Link](javaTime);
[Link]("The SQL TIME is: " +
[Link]());
//Get and display SQL TIMESTAMP
[Link] sqlTimestamp =
new [Link](javaTime);
[Link]("The SQL TIMESTAMP is: " +
[Link]());
}//end main
}//end SqlDateTime
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java SqlDateTime
The Java Date is:Tue Aug 18 13:46:02 GMT+04:00 2009
The SQL DATE is: 2009-08-18
The SQL TIME is: 13:46:02
The SQL TIMESTAMP is: 2009-08-18 13:46:02.828
C:\>
Handling NULL Values
SQL's use of NULL values and Java's use of null are different concepts. So,
to handle SQL NULL values in Java, there are three tactics you can use −
Avoid using getXXX( ) methods that return primitive data types.
Use wrapper classes for primitive data types, and use the ResultSet
object's wasNull( ) method to test whether the wrapper class
variable that received the value returned by the getXXX( ) method
should be set to null.
Use primitive data types and the ResultSet object's wasNull( )
method to test whether the primitive variable that received the
value returned by the getXXX( ) method should be set to an
acceptable value that you've chosen to represent a NULL.
Here is one example to handle a NULL value −
Statement stmt = [Link]( );
String sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = [Link](sql);
int id = [Link](1);
if( [Link]( ) ) {
id = 0;
}
JDBC - Transactions
If your JDBC Connection is in auto-commit mode, which it is by default,
then every SQL statement is committed to the database upon its
completion.
That may be fine for simple applications, but there are three reasons why
you may want to turn off the auto-commit and manage your own
transactions −
To increase performance.
To maintain the integrity of business processes.
To use distributed transactions.
Transactions enable you to control if, and when, changes are applied to
the database. It treats a single SQL statement or a group of SQL
statements as one logical unit, and if any statement fails, the whole
transaction fails.
To enable manual- transaction support instead of the auto-commit mode
that the JDBC driver uses by default, use the Connection
object's setAutoCommit() method. If you pass a boolean false to
setAutoCommit( ), you turn off auto-commit. You can pass a boolean true
to turn it back on again.
For example, if you have a Connection object named conn, code the
following to turn off auto-commit −
[Link](false);
Commit & Rollback
Once you are done with your changes and you want to commit the
changes then call commit() method on connection object as follows −
[Link]( );
Otherwise, to roll back updates to the database made using the
Connection named conn, use the following code −
[Link]( );
The following example illustrates the use of a commit and rollback object
−
try{
//Assume a valid connection object conn
[Link](false);
Statement stmt = [Link]();
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
[Link](SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Singh')";
[Link](SQL);
// If there is no error.
[Link]();
}catch(SQLException se){
// If there is any error.
[Link]();
}
In this case, none of the above INSERT statement would success and
everything would be rolled back.
For a better understanding, let us study the Commit - Example Code.
Using Savepoints
The new JDBC 3.0 Savepoint interface gives you the additional
transactional control. Most modern DBMS, support savepoints within their
environments such as Oracle's PL/SQL.
When you set a savepoint you define a logical rollback point within a
transaction. If an error occurs past a savepoint, you can use the rollback
method to undo either all the changes or only the changes made after the
savepoint.
The Connection object has two new methods that help you manage
savepoints −
setSavepoint(String savepointName) − Defines a new
savepoint. It also returns a Savepoint object.
releaseSavepoint(Savepoint savepointName) − Deletes a
savepoint. Notice that it requires a Savepoint object as a parameter.
This object is usually a savepoint generated by the setSavepoint()
method.
There is one rollback (String savepointName) method, which rolls
back work to the specified savepoint.
The following example illustrates the use of a Savepoint object −
try{
//Assume a valid connection object conn
[Link](false);
Statement stmt = [Link]();
//set a Savepoint
Savepoint savepoint1 = [Link]("Savepoint1");
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
[Link](SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Tez')";
[Link](SQL);
// If there is no error, commit the changes.
[Link]();
}catch(SQLException se){
// If there is any error.
[Link](savepoint1);
}
In this case, none of the above INSERT statement would success and
everything would be rolled back.
For a better understanding, let us study the Savepoints - Example Code.
JDBC - Exceptions
Exception handling allows you to handle exceptional conditions such as
program-defined errors in a controlled fashion.
When an exception condition occurs, an exception is thrown. The term
thrown means that current program execution stops, and the control is
redirected to the nearest applicable catch clause. If no applicable catch
clause exists, then the program's execution ends.
JDBC Exception handling is very similar to the Java Exception handling but
for JDBC, the most common exception you'll deal with
is [Link].
SQLException Methods
An SQLException can occur both in the driver and the database. When
such an exception occurs, an object of type SQLException will be passed
to the catch clause.
The passed SQLException object has the following methods available for retrieving
additional information about the exception −
Method Description
getErrorCode( ) Gets the error number associated with the exception.
Gets the JDBC driver's error message for an error, handled by the
getMessage( )
number and message for a database error.
Gets the XOPEN SQLstate string. For a JDBC driver error, no
getSQLState( ) from this method. For a database error, the five-digit XOPEN SQ
method can return null.
getNextException( ) Gets the next Exception object in the exception chain.
printStackTrace( ) Prints the current exception, or throwable, and it's backtrace to a s
printStackTrace(PrintStream s) Prints this throwable and its backtrace to the print stream you spec
printStackTrace(PrintWriter w) Prints this throwable and it's backtrace to the print writer you spec
By utilizing the information available from the Exception object, you can
catch an exception and continue your program appropriately. Here is the
general form of a try block −
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
Example
Study the following example code to understand the usage
of try....catch...finally blocks.
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "{call getEmpName (?, ?)}";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
CallableStatement stmt = [Link](QUERY);
) {
// Bind values into the parameters.
[Link](1, 1); // This would set ID
// Because second parameter is OUT so register it
[Link](2, [Link]);
//Use execute method to run stored procedure.
[Link]("Executing stored procedure..." );
[Link]();
//Retrieve employee name with getXXX method
String empName = [Link](2);
[Link]("Emp Name with ID: 1 is " +
empName);
} catch (SQLException e) {
[Link]();
}
}
}
Now, let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result if there is
no problem, otherwise the corresponding error would be caught and error
message would be displayed −
C:\>java JDBCExample
Executing stored procedure...
Emp Name with ID: 1 is Zara
C:\>
Try the above example by passing wrong database name or wrong
username or password and check the result.
JDBC - Batch Processing
Batch Processing allows you to group related SQL statements into a batch
and submit them with one call to the database.
When you send several SQL statements to the database at once, you
reduce the amount of communication overhead, thereby improving
performance.
JDBC drivers are not required to support this feature. You should use
the [Link]() method to
determine if the target database supports batch update processing.
The method returns true if your JDBC driver supports this feature.
The addBatch() method of Statement,
PreparedStatement, and CallableStatement is used to add individual
statements to the batch. The executeBatch() is used to start the
execution of all the statements grouped together.
The executeBatch() returns an array of integers, and each
element of the array represents the update count for the respective
update statement.
Just as you can add statements to a batch for processing, you can
remove them with the clearBatch() method. This method removes
all the statements you added with the addBatch() method. However,
you cannot selectively choose which statement to remove.
Batching with Statement Object
Here is a typical sequence of steps to use Batch Processing with
Statement Object −
Create a Statement object using either createStatement() methods.
Set auto-commit to false using setAutoCommit().
Add as many as SQL statements you like into batch
using addBatch() method on created statement object.
Execute all the SQL statements using executeBatch() method on
created statement object.
Finally, commit all the changes using commit() method.
Example
The following code snippet provides an example of a batch update using
Statement object −
// Create statement object
Statement stmt = [Link]();
// Set auto-commit to false
[Link](false);
// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(200,'Zia', 'Ali', 30)";
// Add above SQL statement in the batch.
[Link](SQL);
// Create one more SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(201,'Raj', 'Kumar', 35)";
// Add above SQL statement in the batch.
[Link](SQL);
// Create one more SQL statement
String SQL = "UPDATE Employees SET age = 35 " +
"WHERE id = 100";
// Add above SQL statement in the batch.
[Link](SQL);
// Create an int[] to hold returned values
int[] count = [Link]();
//Explicitly commit statements to apply changes
[Link]();
For a better understanding, let us study the Batching - Example Code.
Batching with PrepareStatement Object
Here is a typical sequence of steps to use Batch Processing with
PrepareStatement Object −
1. Create SQL statements with placeholders.
2. Create PrepareStatement object using
either prepareStatement() methods.
3. Set auto-commit to false using setAutoCommit().
4. Add as many as SQL statements you like into batch
using addBatch() method on created statement object.
5. Execute all the SQL statements using executeBatch() method on
created statement object.
6. Finally, commit all the changes using commit() method.
The following code snippet provides an example of a batch update using
PrepareStatement object −
// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(?, ?, ?, ?)";
// Create PrepareStatement object
PreparedStatemen pstmt = [Link](SQL);
//Set auto-commit to false
[Link](false);
// Set the variables
[Link]( 1, 400 );
[Link]( 2, "Pappu" );
[Link]( 3, "Singh" );
[Link]( 4, 33 );
// Add it to the batch
[Link]();
// Set the variables
[Link]( 1, 401 );
[Link]( 2, "Pawan" );
[Link]( 3, "Singh" );
[Link]( 4, 31 );
// Add it to the batch
[Link]();
//add more batches
.
.
.
.
//Create an int[] to hold returned values
int[] count = [Link]();
//Explicitly commit statements to apply changes
[Link]();
For a better understanding, let us study the Batching - Example Code.
JDBC - Stored Procedure
We have learnt how to use Stored Procedures in JDBC while discussing
the JDBC - Statements chapter. This chapter is similar to that section, but
it would give you additional information about JDBC SQL escape syntax.
Just as a Connection object creates the Statement and PreparedStatement
objects, it also creates the CallableStatement object, which would be used
to execute a call to a database stored procedure.
Creating CallableStatement Object
Suppose, you need to execute the following Oracle stored procedure −
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;
NOTE − Above stored procedure has been written for Oracle, but we are
working with MySQL database so, let us write same stored procedure for
MySQL as follows to create it in EMP database.
DELIMITER $$
DROP PROCEDURE IF EXISTS `EMP`.`getEmpName` $$
CREATE PROCEDURE `EMP`.`getEmpName`
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER ;
Three types of parameters exist − IN, OUT, and INOUT. The
PreparedStatement object only uses the IN parameter. The
CallableStatement object can use all the three.
Here are the definitions of each −
Parameter Description
A parameter whose value is unknown when the SQL statement is crea
IN
parameters with the setXXX() methods.
A parameter whose value is supplied by the SQL statement it returns. You
OUT
parameters with the getXXX() methods.
A parameter that provides both input and output values. You bind variables w
INOUT
retrieve values with the getXXX() methods.
The following code snippet shows how to employ
the [Link]() method to instantiate
a CallableStatement object based on the preceding stored procedure −
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = [Link] (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
The String variable SQL represents the stored procedure, with parameter
placeholders.
Using CallableStatement objects is much like using PreparedStatement
objects. You must bind values to all the parameters before executing the
statement, or you will receive an SQLException.
If you have IN parameters, just follow the same rules and techniques that
apply to a PreparedStatement object; use the setXXX() method that
corresponds to the Java data type you are binding.
When you use OUT and INOUT parameters, you must employ an additional
CallableStatement method, registerOutParameter(). The
registerOutParameter() method binds the JDBC data type to the data type
the stored procedure is expected to return.
Once you call your stored procedure, you retrieve the value from the OUT
parameter with the appropriate getXXX() method. This method casts the
retrieved value of SQL type to a Java data type.
Closing CallableStatement Object
Just as you close other Statement object, for the same reason you should
also close the CallableStatement object.
A simple call to the close() method will do the job. If you close the
Connection object first, it will close the CallableStatement object as well.
However, you should always explicitly close the CallableStatement object
to ensure proper cleanup.
CallableStatement cstmt = null;
try {
String SQL = "{call getEmpName (?, ?)}";
cstmt = [Link] (SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
[Link]();
}
studyWe have studied more details in the Callable - Example Code.
JDBC SQL Escape Syntax
The escape syntax gives you the flexibility to use database specific
features unavailable to you by using standard JDBC methods and
properties.
The general SQL escape syntax format is as follows −
{keyword 'parameters'}
Here are the following escape sequences, which you would find very
useful while performing the JDBC programming −
d, t, ts Keywords
They help identify date, time, and timestamp literals. As you know, no two
DBMSs represent time and date the same way. This escape syntax tells
the driver to render the date or time in the target database's format. For
Example −
{d 'yyyy-mm-dd'}
Where yyyy = year, mm = month; dd = date. Using this syntax {d '2009-
09-03'} is March 9, 2009.
Here is a simple example showing how to INSERT date in a table −
//Create a Statement object
stmt = [Link]();
//Insert data ==> ID, First Name, Last Name, DOB
String sql="INSERT INTO STUDENTS VALUES" +
"(100,'Zara','Ali', {d '2001-12-16'})";
[Link](sql);
Similarly, you can use one of the following two syntaxes, either t or ts −
{t 'hh:mm:ss'}
Where hh = hour; mm = minute; ss = second. Using this syntax {t
'13:30:29'} is 1:30:29 PM.
{ts 'yyyy-mm-dd hh:mm:ss'}
This is combined syntax of the above two syntax for 'd' and 't' to
represent timestamp.
escape Keyword
This keyword identifies the escape character used in LIKE clauses. Useful
when using the SQL wildcard %, which matches zero or more characters.
For example −
String sql = "SELECT symbol FROM MathSymbols
WHERE symbol LIKE '\%' {escape '\'}";
[Link](sql);
If you use the backslash character (\) as the escape character, you also
have to use two backslash characters in your Java String literal, because
the backslash is also a Java escape character.
fn Keyword
This keyword represents scalar functions used in a DBMS. For example,
you can use SQL function length to get the length of a string −
{fn length('Hello World')}
This returns 11, the length of the character string 'Hello World'.
call Keyword
This keyword is used to call the stored procedures. For example, for a
stored procedure requiring an IN parameter, use the following syntax −
{call my_procedure(?)};
For a stored procedure requiring an IN parameter and returning an OUT
parameter, use the following syntax −
{? = call my_procedure(?)};
oj Keyword
This keyword is used to signify outer joins. The syntax is as follows −
{oj outer-join}
Where outer-join = table {LEFT|RIGHT|FULL} OUTERJOIN {table | outer-
join} on search-condition. For example −
String sql = "SELECT Employees
FROM {oj ThisTable RIGHT
OUTER JOIN ThatTable on id = '100'}";
[Link](sql);
JDBC - Streaming Data
A PreparedStatement object has the ability to use input and output
streams to supply parameter data. This enables you to place entire files
into database columns that can hold large values, such as CLOB and BLOB
data types.
There are following methods, which can be used to stream data −
setAsciiStream() − This method is used to supply large ASCII
values.
setCharacterStream() − This method is used to supply large
UNICODE values.
setBinaryStream() − This method is used to supply large binary
values.
The setXXXStream() method requires an extra parameter, the file size,
besides the parameter placeholder. This parameter informs the driver how
much data should be sent to the database using the stream.
This example would create a database table XML_Data and then XML
content would be written into this table.
Copy and paste the following example in [Link], compile
and run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class TestApplication {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT Data FROM XML_Data
WHERE id=100";
static final String INSERT_QUERY="INSERT INTO XML_Data
VALUES (?,?)";
static final String CREATE_TABLE_QUERY = "CREATE TABLE
XML_Data (id INTEGER, Data LONG)";
static final String DROP_TABLE_QUERY = "DROP TABLE
XML_Data";
static final String XML_DATA =
"<Employee><id>100</id><first>Zara</first><last>Ali</last><Sal
ary>10000</Salary><Dob>18-08-1978</Dob></Employee>";
public static void createXMLTable(Statement stmt)
throws SQLException{
[Link]("Creating XML_Data table..." );
//Drop table first if it exists.
try{
[Link](DROP_TABLE_QUERY);
}catch(SQLException se){
}
[Link](CREATE_TABLE_QUERY);
}
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
PreparedStatement pstmt =
[Link](INSERT_QUERY);
) {
createXMLTable(stmt);
ByteArrayInputStream bis = new
ByteArrayInputStream(XML_DATA.getBytes());
[Link](1,100);
[Link](2,bis,XML_DATA.getBytes().length
);
[Link]();
//Close input stream
[Link]();
ResultSet rs = [Link](QUERY);
// Get the first row
if ([Link] ()){
//Retrieve data from input stream
InputStream xmlInputStream = [Link]
(1);
int c;
ByteArrayOutputStream bos = new
ByteArrayOutputStream();
while (( c = [Link] ()) != -1)
[Link](c);
//Print results
[Link]([Link]());
}
// Clean-up environment
[Link]();
} catch (SQLException | IOException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run FirstApplication, it produces the following result −
C:\>java FirstApplication
Creating XML_Data table...
<Employee><id>100</id><first>Zara</first><last>Ali</
last><Salary>10000</Salary><Dob>18-08-1978</Dob></Employee>
C:\>
JDBC - Create Database
This tutorial provides an example on how to create a Database using JDBC
application. Before executing the following example, make sure you have
the following in place −
You should have admin privilege to create a database in the given
schema. To execute the following example, you need to replace
the username and password with your actual user name and
password.
Your MySQL or whatever database is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with the database
server.
To create a new database, you need not give any database name
while preparing database URL as mentioned in the below example.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to the database.
Clean up the environment . try with resources automatically
closes the resources.
Sample Code
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
) {
String sql = "CREATE DATABASE STUDENTS";
[Link](sql);
[Link]("Database created
successfully...");
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Database created successfully...
C:\>
JDBC - Select Database
This chapter provides an example on how to select a Database using JDBC
application. Before executing the following example, make sure you have
the following in place −
To execute the following example you need to replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using, is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for the database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with
a selected database.
Selection of database is made while you prepare database URL.
Following example would make connection
with STUDENTS database.
Clean up the environment − try with resources automatically
closes the resources.
Sample Code
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
[Link]("Connecting to a selected
database...");
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);) {
[Link]("Connected database
successfully...");
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
C:\>
JDBC - Drop Database
This chapter provides an example on how to drop an existing Database
using JDBC application. Before executing the following example, make
sure you have the following in place −
To execute the following example you need to replace
the username and password with your actual user name and
password.
Your MySQL is up and running.
NOTE: This is a serious operation and you have to make a firm decision
before proceeding to delete a database because everything you have in
your database would be lost.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Deleting a database does not require database name to be in your
database URL. Following example would
delete STUDENTS database.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to delete the database.
Clean up the environment − try with resources automatically
closes the resources.
Sample Code
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
) {
String sql = "DROP DATABASE STUDENTS";
[Link](sql);
[Link]("Database dropped
successfully...");
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Database dropped successfully...
C:\>
JDBC - Create Tables
This chapter provides an example on how to create a table using JDBC
application. Before executing the following example, make sure you have
the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to create a table in a
seleted database.
Clean up the environment − try with resources automatically
closes the resources.
Sample Code
Copy and paste the following example in [Link], compile
and run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class TestApplication {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
) {
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
[Link](sql);
[Link]("Created table in given
database...");
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Created table in given database...
C:\>
JDBC - Drop Tables
This chapter provides an example on how to delete a table using JDBC
application. Before executing the following example, make sure you have
the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using, is up and running.
NOTE Reformatting JDBC Tutorial This is a serious operation and you have
to make a firm decision before proceeding to delete a table, because
everything you have in your table would be lost.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a queryReformatting JDBC Tutorial Requires using an
object of type Statement for building and submitting an SQL
statement to drop a table in a seleted database.
Clean up the environment Reformatting JDBC Tutorial try with
resources automatically closes the resources.
Sample Code
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
) {
String sql = "DROP TABLE REGISTRATION";
[Link](sql);
[Link]("Table deleted in given
database...");
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Table deleted in given database...
C:\>
JDBC - Insert Records
This chapter provides an example on how to insert records in a table using
JDBC application. Before executing following example, make sure you
have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Register the JDBC driver − Requires that you initialize a driver so
you can open a communications channel with the database.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to insert records into a
table.
Clean up the environment try with resources automatically closes
the resources.
Sample Code
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
) {
// Execute a query
[Link]("Inserting records into the
table...");
String sql = "INSERT INTO Registration VALUES (100,
'Zara', 'Ali', 18)";
[Link](sql);
sql = "INSERT INTO Registration VALUES (101,
'Mahnaz', 'Fatma', 25)";
[Link](sql);
sql = "INSERT INTO Registration VALUES (102, 'Zaid',
'Khan', 30)";
[Link](sql);
sql = "INSERT INTO Registration VALUES(103, 'Sumit',
'Mittal', 28)";
[Link](sql);
[Link]("Inserted records into the
table...");
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Inserting records into the table...
Inserted records into the table...
C:\>
JDBC - Select Records
This chapter provides an example on how to select/ fetch records from a
table using JDBC application. Before executing the following example,
make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to select (i.e. fetch )
records from a table.
Extract Data − Once SQL query is executed, you can fetch records
from the table.
Clean up the environment − try with resources automatically
closes the resources.
Sample Code
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age
FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
ResultSet rs = [Link](QUERY);
) {
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " +
[Link]("first"));
[Link](", Last: " +
[Link]("last"));
}
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
JDBC - Update Records
This chapter provides an example on how to update records in a table
using JDBC application. Before executing the following example, make
sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to update records in a
table. This Query makes use of IN and WHERE clause to update
conditional records.
Clean up the environment − try with resources automatically
closes the resources.
Sample Code
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age
FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
) {
String sql = "UPDATE Registration " +
"SET age = 30 WHERE id in (100, 101)";
[Link](sql);
ResultSet rs = [Link](QUERY);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " +
[Link]("first"));
[Link](", Last: " +
[Link]("last"));
}
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 101, Age: 30, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
JDBC - Delete Records
This chapter provides an example on how to delete records from a table
using JDBC application. Before executing following example, make sure
you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Register the JDBC driver − Requires that you initialize a driver so
you can open a communications channel with the database.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to delete records from a
table. This Query makes use of the WHERE clause to delete
conditional records.
Clean up the environment − try with resources automatically
closes the resources.
Sample Code
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age
FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();
) {
String sql = "DELETE FROM Registration " +
"WHERE id = 101";
[Link](sql);
ResultSet rs = [Link](QUERY);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " +
[Link]("first"));
[Link](", Last: " +
[Link]("last"));
}
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
JDBC - WHERE Clause
This chapter provides an example on how to select records from a table
using JDBC application. This would add additional conditions using WHERE
clause while selecting records from the table. Before executing the
following example, make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using, is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for the database programming.
Most often, using import [Link].* will suffice.
Register the JDBC driver − Requires that you initialize a driver so
you can open a communications channel with the database.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to fetch records from a
table, which meet the given condition. This Query makes use of
the WHERE clause to select records.
Clean up the environment − try with resources automatically
closes the resources.
Sample Code
Copy and paste the following example in [Link], compile
and run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class TestApplication {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age
FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();) {
[Link]("Fetching records without
condition...");
ResultSet rs = [Link](QUERY);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " +
[Link]("first"));
[Link](", Last: " +
[Link]("last"));
}
// Select all records having ID equal or greater than
101
[Link]("Fetching records with
condition...");
String sql = "SELECT id, first, last, age FROM
Registration" +
" WHERE id >= 101 ";
rs = [Link](sql);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " +
[Link]("first"));
[Link](", Last: " +
[Link]("last"));
}
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run TestApplication, it produces the following result −
C:\>java TestApplication
Fetching records without condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Fetching records with condition...
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
JDBC - Like Clause
This chapter provides an example on how to select records from a table
using JDBC application. This would add additional conditions using LIKE
clause while selecting records from the table. Before executing the
following example, make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using, is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to fetch records from a
table which meet given condition. This Query makes use
of LIKE clause to select records to select all the students whose first
name starts with "za".
Clean up the environment − try with resources automatically
closes the resources.
Sample Code
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age
FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();) {
[Link]("Fetching records without
condition...");
ResultSet rs = [Link](QUERY);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " +
[Link]("first"));
[Link](", Last: " +
[Link]("last"));
}
// Select all records having ID equal or greater than
101
[Link]("Fetching records with
condition...");
String sql = "SELECT id, first, last, age FROM
Registration" +
" WHERE first LIKE '%za%'";
rs = [Link](sql);
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " +
[Link]("first"));
[Link](", Last: " +
[Link]("last"));
}
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Fetching records without condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
Fetching records with condition...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
C:\>
JDBC - Sorting Data
This chapter provides an example on how to sort records from a table
using JDBC application. This would use asc and desc keywords to sort
records in ascending or descending order. Before executing the following
example, make sure you have the following in place −
To execute the following example you can replace
the username and password with your actual user name and
password.
Your MySQL or whatever database you are using, is up and running.
Required Steps
The following steps are required to create a new Database using JDBC
application −
Import the packages − Requires that you include the packages
containing the JDBC classes needed for database programming.
Most often, using import [Link].* will suffice.
Open a connection − Requires using
the [Link]() method to create a Connection
object, which represents a physical connection with a database
server.
Execute a query − Requires using an object of type Statement for
building and submitting an SQL statement to sort records from a
table. These Queries make use of asc and desc clauses to sort data
in ascending and descening orders.
Clean up the environment − try with resources automatically
closes the resources.
Sample Code
Copy and paste the following example in [Link], compile and
run as follows −
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBCExample {
static final String DB_URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age
FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn =
[Link](DB_URL, USER, PASS);
Statement stmt = [Link]();) {
[Link]("Fetching records in ascending
order...");
ResultSet rs = [Link](QUERY + " ORDER BY
first ASC");
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " +
[Link]("first"));
[Link](", Last: " +
[Link]("last"));
}
[Link]("Fetching records in descending
order...");
rs = [Link](QUERY + " ORDER BY first
DESC");
while([Link]()){
//Display values
[Link]("ID: " + [Link]("id"));
[Link](", Age: " + [Link]("age"));
[Link](", First: " +
[Link]("first"));
[Link](", Last: " +
[Link]("last"));
}
[Link]();
} catch (SQLException e) {
[Link]();
}
}
}
Now let us compile the above example as follows −
C:\>javac [Link]
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Fetching records in ascending order...
ID: 103, Age: 28, First: Sumit, Last: Mittal
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 100, Age: 30, First: Zara, Last: Ali
Fetching records in descending order...
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
[Link]
Design of JDBC
Java Database Connectivity (JDBC) is an Application Programming Interface (API), from Sun microsystem tha
relational databases from different vendors. JDBC and database drivers work in tandem to access spreadsheets an
JDBC, which is used for connecting to the database.
Components of JDBC
JDBC has four major components that are used for the interaction with the database.
1. JDBC API
2. JDBC Test Suite
3. JDBC Driver Manger
4. JDBC ODBC Bridge Driver
1) JDBC API: JDBC API provides various interfaces and methods to establish easy connection with different dat
[Link].*;
[Link].*;
2) JDBC Test suite: JDBC Test suite facilitates the programmer to test the various operations such as deletion,
Drivers.
3) JDBC Driver manager: JDBC Driver manager loads the database-specific driver into an application in order
Driver manager is also used to make the database-specific call to the database in order to do the processing of a us
4) JDBC-ODBC Bridge Drivers: JDBC-ODBC Bridge Drivers are used to connect the database drivers to th
method calls into the ODBC method call. It makes the usage of the [Link] package that encompasses the n
Connectivity) characteristics.
Note: Since Java 8, the JDBC-ODBC drivers have been removed. Oracle suggests
the database.
Architecture of JDBC
1) Application: It is the Java servlet or an applet that communicates with the data source.
2) The JDBC API: It allows the Java programs to perform the execution of the SQL statements and then get the r
A few of the crucial interfaces and classes defined in the JDBC API are the following:
o Drivers
o DriverManager
o Statement
o Connection
o CallableStatement
o PreparedStatement
o ResultSet
o SQL data
3) DriverManager: DriverManager plays a crucial role in the architecture of JDBC.
It uses database-specific drivers to connect the enterprise applications to various databases.
4) JDBC drivers: To interact with a data source with the help of the JDBC, one needs a JDBC driver which conv
Different Types of Architecture of JDBC
The architecture of the JDBC consists of two and three tiers model in order to access the given database.
Two-tier model: In this model, the application interacts directly with the source of data. The JDBC driver est
application. When a query is sent by the user to the data source, the reply of those sent queries is sent directly to th
The source of data can be located on a different machine, and that machine is connected to the user machine follo
is sending the query is the client machine, and the machine that is sending the result of those queries is acting as th
Three-tier model: In this model, the queries of the user are being sent to the middle-tier services, from where
answers to those queries are reverted to the middle tier, and from there, it is again sent to the user.
JDBC Working
Any Java application that needs to interact with a database needs to be programmed using the JDBC API. The J
MySql needs to be added; then, only the interaction happens with the data source.
FileName: [Link]
// required import statements
import [Link].*;
public class JDBCExample
{
// URL for establishing the connection to the database
// TCP port number is 3306
// Name of the database is mydb
final static String DB_URL = "jdbc:mysql://localhost:3306/mydb";
// Mysql driver class
10. final static String DB_DRIVER = "[Link]";
11. // Password and User name for using the database
12. static String uName = "root";
13. static String psd = "root";
14. // main method
15. public static void main(String argvs[])
16. {
17. Connection conn = null; // for establishing connection
18. String query = null; // for storing the queries
19. Statement sttment = null; // for executing the query
20. ResultSet resultSet = null; // for storing the response of query
21. try
22. {
23. // Registering the database driver
24. [Link](DB_DRIVER);
25. [Link]("Database connection established");
26. // Creating a connection to the database
27. conn = [Link](DB_URL, uName, psd);
28. // the query be executed
29. // EmployeeId, EmployeeName, Department are the fields or column names
30. // mytable is the table name available in the mydb database
31. query = "select EmployeeId, EmployeeName, Department from mytable";
32. // for query execution
33. sttment = [Link]();
34. // the query is executed and the result is stored
35. resultSet = [Link](query);
36. while([Link]() )
37. {
38. // receiving the results using the table column name
39. int eId = [Link]("EmployeeId");
40. String eName = [Link]("EmployeeName");
41. String department = [Link]("Department");
42.
43. // printing the values
44. [Link]("Employee ID: " + eId);
45. [Link](", Employee Name: " + eName);
46. [Link](", Department: " + department);
47. }
48. }
49. catch(SQLException sqlExp)
50. {
51. // For handling the exception raised from JDBC
52. [Link]();
53. }
54. catch(Exception e)
55. {
56. // For handing the issues raised from [Link]
57. [Link]();
58. }
59. finally
60. {
61. try
62. {
63. // performing the clean-up work
64. // terminating the connection
65. [Link]();
66. [Link]();
67. [Link]();
68. [Link]("The Connection is closed.");
69. }
70. catch(SQLException sqlExp)
71. {
72. [Link]();
73. }
74. }
75. }
76. }
Output:
Database connection established
Employee ID: 100, Employee Name: Nitesh Singh, Department: Project Management
Employee ID: 104, Employee Name: Amit Kumar, Department: Game Development
Employee ID: 105, Employee Name: Amrit Kumar, Department: Database Management
Employee ID: 109, Employee Name: Rohit Kumar, Department: Software Testing
Employee ID: 120, Employee Name: Ajeet Chouhan, Department: Software Design
Employee ID: 155, Employee Name: Aman Jatt, Department: Art Integration
The Connection is closed.
Explanation: The above Java application connects to the MySQL Database System. Therefore, we need the dr
([Link]) is provided in the [Link] file, which must be included in the classpath whe
MySQL had we used Oracle, then the drivers corresponding to Oracle must be used.
Next TopicJava Anon Proxy
← prevnext →
Learn Important Tutorial
Python
Java
Javascript
HTML
Database
PHP
C++
React
[Link] / MCA
DBMS
Data Structures
DAA
Operating System
Computer Network
Compiler Design
Computer Organization
Discrete Mathematics
Ethical Hacking
Computer Graphics
Web Technology
Software Engineering
Cyber Security
Automata
C Programming
C++
Java
.Net
Python
Programs
Control System
Data Warehouse
Preparation
Aptitude
Reasoning
Verbal Ability
Interview Questions
Company Questions
Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to follow 5 following
steps.
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
1. Driver class: The driver class for the mysql database is [Link].
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the
database, localhost is the server name on which mysql is running, we may also
use IP address, 3306 is the port number and sonoo is the database name. We
may use any database, in such case, we need to replace the sonoo with our
database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to
create database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
Example to Connect Java Application with mysql
database
In this example, sonoo is the database name, root is the username and password both.
1. import [Link].*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6. Connection con=[Link](
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=[Link]();
10. ResultSet rs=[Link]("select * from emp");
11. while([Link]())
12. [Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
13. [Link]();
14. }catch(Exception e){ [Link](e);}
15. }
16. }
download this example
The above example will fetch all the records of emp table.
To connect java application with the mysql database, [Link] file is
required to be loaded.
download the jar file [Link]
Two ways to load the jar file:
1. Paste the [Link] file in jre/lib/ext folder
2. Set classpath
1) Paste the [Link] file in JRE/lib/ext folder:
Download the [Link] file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath:
There are two ways to set the classpath:
temporary
permanent
How to set the temporary classpath
open command prompt and write:
1. C:>set classpath=c:\folder\[Link];.;
How to set the permanent classpath
Go to environment variable then click on new tab. In variable name write classpath and
in variable value paste the path to the [Link] file by appending
[Link];.; as C:\folder\[Link];.;
Java Database Connectivity with MySQL MCQ
1. Which driver class is used to connect to a MySQL database in Java?
1. [Link]
2. [Link]
3. [Link]
4. [Link]
Show Answer Workspace
2. Which method is used to establish a connection to the database?
1. [Link]()
2. [Link]()
3. [Link]()
4. [Link]()
Show Answer Workspace
3. Which of the following is the correct URL to connect to a MySQL database
named 'testdb'?
Advertisement
1. jdbc:mysql://localhost:3306/testdb
2. jdbc:mysql://localhost/testdb
3. mysql://localhost:3306/testdb
4. jdbc:mysql:localhost:3306/testdb
Show Answer Workspace
4. What is the role of the Statement interface in JDBC?
1. To execute SQL queries
2. To establish a database connection
3. To close the database connection
4. To load the database driver
Show Answer Workspace
5. Which method is used to execute a SELECT query in JDBC?
1. executeQuery()
2. execute()
3. executeUpdate()
4. runQuery()
Show Answer Workspace
Accessing a Microsoft Access database without using a Data Source Name (DSN)
is often preferred in scenarios where portability, simplicity, or avoiding system-level
configuration is essential. It can be achieved through a DSN-less connection, which
allows a Java program to directly specify the connection parameters, bypassing the
need for a pre-configured DSN.
In Java, connectivity with a Microsoft Access database is typically done using the JDBC-
ODBC Bridge or a third-party library like UCanAccess. As the JDBC-ODBC bridge has
been deprecated in newer versions of Java, UCanAccess is a popular alternative that
offers robust support for Access databases.
Key Components of DSN-less Connection
1. Driver Specification: A JDBC driver must be specified explicitly. For Access
databases, the UCanAccess JDBC driver is commonly used.
2. Database Path: The absolute or relative file path to the Access database file
(.mdb or .accdb) is directly provided in the connection URL.
3. Dependencies: UCanAccess requires certain libraries ([Link],
[Link], etc.) to be included in the project.
4. Connection URL Format: The connection URL includes the database file path
and optional configurations.
Advantages of DSN-less Connection
1. Portability: No need for DSN configuration on every system where the
application runs.
2. Ease of Setup: Eliminates reliance on administrative tools or registry settings for
configuration.
3. Dynamic Connections: Database paths can be easily changed
programmatically.
Example of DSN-less Connection Using Java and UCanAccess
Database File: [Link]
ID Name
1 Alice
2 Bob
3 Charlie
File Name: [Link]
Backward Skip 10sPlay VideoForward Skip 10s
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. public class AccessDatabaseConnection {
6. public static void main(String[] args) {
7. // Path to the Microsoft Access database file
8. String dbFilePath = "C:/databases/[Link]";
9. // Connection URL for UCanAccess driver
10. String jdbcURL = "jdbc:ucanaccess://" + dbFilePath;
11. // Database operations
12. try (Connection connection = [Link](jdbcURL)) {
13. [Link]("Connection established successfully.");
14. // Create a statement
15. Statement statement = [Link]();
16. // Execute a query to retrieve data from Employees table
17. String query = "SELECT ID, Name FROM Employees";
18. ResultSet resultSet = [Link](query);
19. // Process the result set
20. [Link]("Employee Details:");
21. while ([Link]()) {
22. [Link]("ID: " + [Link]("ID"));
23. [Link]("Name: " + [Link]("Name"));
24. }
25. // Close resources
26. [Link]();
27. [Link]();
28. } catch (Exception e) {
29. [Link]();
30. }
31. }
32. }
Output:
Connection established successfully.
Employee Details:
ID: 1
Name: Alice
ID: 2
Name: Bob
ID: 3
Name: Charlie
Explanation
The provided code demonstrates a simple way to connect to an Access database file
without using a DSN. It starts by specifying the file path of the database, which is directly
embedded into the JDBC URL.
The UCanAccess JDBC driver is used to establish the connection. After successfully
connecting, the program executes an SQL query on a specified table, retrieves the
results, and prints them to the console. The try-with-resources statement ensures that
the database connection is closed automatically, avoiding potential memory leaks.
This approach minimizes external dependencies and makes the application
configuration-free for database connectivity.
Steps to Set Up and Run the Code
1. Download UCanAccess:
Advertisement
o Visit the official [UCanAccess]([Link] website.
o Download the latest version of the UCanAccess library.
2. Add Dependencies
Include the following JAR files in your project:
o [Link]
o [Link]
o [Link]
o [Link]
o [Link]
Note: If using an IDE like Eclipse or IntelliJ, add these files to the
project's build path.
3. Prepare the Database
Ensure the .accdb or .mdb file exists and has a valid schema (tables, columns, etc.).
4. Run the Program
o Compile and execute the Java program.
o Ensure the file path to the Access database is correct.
o Check the console output for query results or connection issues.
UCanAccess Features and Configuration Options
o Read/Write Operations: UCanAccess supports all common SQL operations, such
as SELECT, INSERT, UPDATE, and DELETE.
o Data Integrity: Handles data types, constraints, and relationships defined in the
Access database.
o Encryption Support: It can connect to password-protected Access databases by
appending ;jackcessOpener=YourOpenerClass to the connection URL.
o Logging: It supports detailed logging of SQL queries and transactions.
Customizing the Connection URL
The connection URL can be customized for various purposes:
1. Read-Only Mode
Advertisement
1. String jdbcURL = "jdbc:ucanaccess://" + dbFilePath + ";openExclusive=true";
It ensures no other application can access the database simultaneously.
2. Password-Protected Database
1. String jdbcURL = "jdbc:ucanaccess://" + dbFilePath + ";jackcessOpener=YourOpener
Class";
Replace YourOpenerClass with the appropriate handler for decrypting the database.
Advertisement
3. Memory Settings
1. Add ;memory=true to improve performance for in-memory operations.
Best Practices for DSN-less Connections
1. Use Relative Paths: For portability, use relative file paths instead of hardcoded
absolute paths.
String dbFilePath = "./data/[Link]";
2. Error Handling: Implement detailed error logging to identify issues during
connection or query execution.
3. Connection Pooling: For high-performance applications, integrate a connection
pooling library to manage database connections efficiently.
4. Thread Safety: Ensure thread-safe operations when accessing the database
concurrently.
Conclusion
Connecting to an Access database without a DSN is straightforward and provides
flexibility for Java applications. The UCanAccess library simplifies this process by
offering a robust JDBC driver with extensive functionality.
By avoiding DSN configurations, developers can achieve greater portability and reduced
setup complexity, making this approach ideal for lightweight and easily deployable
solutions.
DriverManager class
The DriverManager class is the component of JDBC API and also a member of
the [Link] package. The DriverManager class acts as an interface between users and
drivers. It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver. It contains all the appropriate
methods to register and deregister the database driver class and to create a connection
between a Java application and the database. The DriverManager class maintains a list
of Driver classes that have registered themselves by calling the method
[Link](). Note that before interacting with a Database, it is a
mandatory process to register the driver; otherwise, an exception is thrown.
Methods of the DriverManager Class
Method Description
is used to register the given driver with
1) public static synchronized void DriverManager. No action is performed by
registerDriver(Driver driver): the method when the given driver is already
registered.
2) public static synchronized void is used to deregister the given driver (drop
deregisterDriver(Driver driver): the driver from the list) with DriverManager.
If the given driver has been removed from
the list, then no action is performed by the
method.
is used to establish the connection with the
3) public static Connection specified url. The SQLException is thrown
getConnection(String url) throws when the corresponding Driver class of the
SQLException: given database is not registered with the
DriverManager.
is used to establish the connection with the
4) public static Connection specified url, username, and password. The
getConnection(String url,String SQLException is thrown when the
userName,String password) throws corresponding Driver class of the given
SQLException: database is not registered with the
DriverManager.
Those drivers that understand the
mentioned URL (present in the parameter
5) public static Driver getDriver(String
of the method) are returned by this method
url)
provided those drivers are mentioned in the
list of registered drivers.
The duration of time a driver is allowed to
6) pubic static int getLoginTimeout() wait in order to establish a connection with
the database is returned by this method.
The method provides the time in seconds.
sec mentioned in the parameter is the
maximum time that a driver is allowed to
7) pubic static void setLoginTimeout(int wait in order to establish a connection with
sec) the database. If 0 is passed in the
parameter of this method, the driver will
have to wait infinitely while trying to
establish the connection with the database.
8) public static Connection A connection object is returned by this
getConnection(String URL, Properties method after creating a connection to the
prop) throws SQLException database present at the mentioned URL,
which is the first parameter of this method.
The second parameter, which is "prop",
fetches the authentication details of the
database (username and password.).
Similar to the other variation of the
getConnection() method, this method also
throws the SQLException, when the
corresponding Driver class of the given
database is not registered with the
DriverManager.
Next TopicConnection Interface
Connection interface
A Connection is a session between a Java application and a database. It helps to
establish a connection with the database.
The Connection interface is a factory of Statement, PreparedStatement, and
DatabaseMetaData, i.e., an object of Connection can be used to get the object of
Statement and DatabaseMetaData. The Connection interface provide many methods for
transaction management like commit(), rollback(), setAutoCommit(),
setTransactionIsolation(), etc.
By default, connection commits the changes after executing queries.
Commonly used methods of Connection interface:
1) public Statement createStatement(): creates a statement object that can be used to
execute SQL queries.
2) public Statement createStatement(int resultSetType,int
resultSetConcurrency): Creates a Statement object that will generate ResultSet
objects with the given type and concurrency.
Backward Skip 10sPlay VideoForward Skip 10s
3) public void setAutoCommit(boolean status): is used to set the commit status. By
default, it is true.
4) public void commit(): saves the changes made since the previous commit/rollback is
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources
immediately.
Connection Interface Fields
There are some common Connection interface constant fields that are present in the
Connect interface. These fields specify the isolation level of a transaction.
TRANSACTION_NONE: No transaction is supported, and it is indicated by this constant.
TRANSACTION_READ_COMMITTED: It is a constant which shows that the dirty reads
are not allowed. However, phantom reads and non-repeatable reads can occur.
TRANSACTION_READ_UNCOMMITTED: It is a constant which shows that dirty reads,
non-repeatable reads, and phantom reads can occur.
TRANSACTION_REPEATABLE_READ: It is a constant which shows that the non-
repeatable reads and dirty reads are not allowed. However, phantom reads and can
occur.
TRANSACTION_SERIALIZABLE: It is a constant which shows that the non-repeatable
reads, dirty reads as well as the phantom reads are not allowed.
Statement interface
The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the
object of ResultSet.
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the o
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, dro
3) public boolean execute(String sql): is used to execute queries that may return multiple results
4) public int[] executeBatch(): is used to execute batch of commands.
Example of Statement interface
Let’s see the simple example of Statement interface to insert, update and delete the
record.
1. import [Link].*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4. [Link]("[Link]");
5. Connection con=[Link]("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");
6. Statement stmt=[Link]();
7.
8. //[Link]("insert into emp765 values(33,'Irfan',50000)");
9. //int result=[Link]("update emp765 set name='Vimal',salary=100
00 where id=33");
10. int result=[Link]("delete from emp765 where id=33");
11. [Link](result+" records affected");
12. [Link]();
13. }}
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.
By default, ResultSet object can be moved forward only and it is not
updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as updatable by:
1. Statement stmt = [Link](ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);
Commonly used methods of ResultSet interface
is used to move the cursor to the one row
1) public boolean next():
next from the current position.
is used to move the cursor to the one row
2) public boolean previous():
previous from the current position.
is used to move the cursor to the first row in
3) public boolean first():
result set object.
is used to move the cursor to the last row in
4) public boolean last():
result set object.
is used to move the cursor to the specified
5) public boolean absolute(int row):
row number in the ResultSet object.
is used to move the cursor to the relative row
6) public boolean relative(int row): number in the ResultSet object, it may be
positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified column
index of the current row as int.
is used to return the data of specified column
8) public int getInt(String columnName):
name of the current row as int.
9) public String getString(int is used to return the data of specified column
columnIndex): index of the current row as String.
10) public String getString(String is used to return the data of specified column
columnName): name of the current row as String.
Example of Scrollable ResultSet
Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
1. import [Link].*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. [Link]("[Link]");
6. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe"
,"system","oracle");
7. Statement stmt=[Link](ResultSet.TYPE_SCROLL_SENSITIVE,Result
Set.CONCUR_UPDATABLE);
8. ResultSet rs=[Link]("select * from emp765");
9.
10. //getting the record of 3rd row
11. [Link](3);
12. [Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
13.
14. [Link]();
15. }}
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
Backward Skip 10sPlay VideoForward Skip 10s
How to get the instance of PreparedStatement?
The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:
1. public PreparedStatement prepareStatement(String query)throws SQLException{}
Methods of PreparedStatement interface
The important methods of PreparedStatement interface are given below:
Method Description
public void setInt(int paramIndex, int value) sets the integer value to th
public void setString(int paramIndex, String value) sets the String value to the
public void setFloat(int paramIndex, float value) sets the float value to the g
public void setDouble(int paramIndex, double value) sets the double value to th
public int executeUpdate() executes the query. It is us
public ResultSet executeQuery() executes the select query.
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:
1. import [Link].*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6.
7. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe"
,"system","oracle");
8.
9. PreparedStatement stmt=[Link]("insert into Emp values(?,?)");
10. [Link](1,101);//1 specifies the first parameter in the query
11. [Link](2,"Ratan");
12.
13. int i=[Link]();
14. [Link](i+" records inserted");
15.
16. [Link]();
17.
18. }catch(Exception e){ [Link](e);}
19.
20. }
21. }
download this example
Example of PreparedStatement interface that updates the record
1. PreparedStatement stmt=[Link]("update emp set name=? where id=
?");
2. [Link](1,"Sonoo");//1 specifies the first parameter in the query i.e. name
3. [Link](2,101);
4.
5. int i=[Link]();
6. [Link](i+" records updated");
download this example
Example of PreparedStatement interface that deletes the record
1. PreparedStatement stmt=[Link]("delete from emp where id=?");
2. [Link](1,101);
3.
4. int i=[Link]();
5. [Link](i+" records deleted");
download this example
Example of PreparedStatement interface that retrieve the records of
a table
1. PreparedStatement stmt=[Link]("select * from emp");
2. ResultSet rs=[Link]();
3. while([Link]()){
4. [Link]([Link](1)+" "+[Link](2));
5. }
download this example
Example of PreparedStatement to insert records until user press n
1. import [Link].*;
2. import [Link].*;
3. class RS{
4. public static void main(String args[])throws Exception{
5. [Link]("[Link]");
6. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe"
,"system","oracle");
7.
8. PreparedStatement ps=[Link]("insert into emp130 values(?,?,?)");
9.
10. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
11.
12. do{
13. [Link]("enter id:");
14. int id=[Link]([Link]());
15. [Link]("enter name:");
16. String name=[Link]();
17. [Link]("enter salary:");
18. float salary=[Link]([Link]());
19.
20. [Link](1,id);
21. [Link](2,name);
22. [Link](3,salary);
23. int i=[Link]();
24. [Link](i+" records affected");
25.
26. [Link]("Do you want to continue: y/n");
27. String s=[Link]();
28. if([Link]("n")){
29. break;
30. }
31. }while(true);
32.
33. [Link]();
34. }}
Java ResultSetMetaData Interface
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column
type etc. , ResultSetMetaData interface is useful because it provides methods to get
metadata from the ResultSet object.
Commonly Used Methods Of Resultsetmetadata Interface
Method Description
public int getColumnCount()throws SQLException It returns the total numbe
public String getColumnName(int index)throws SQLException It returns the column nam
public String getColumnTypeName(int index)throws SQLException It returns the column typ
public String getTableName(int index)throws SQLException It returns the table name
How to get the object of ResultSetMetaData:
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax:
1. public ResultSetMetaData getMetaData()throws SQLException
Example of ResultSetMetaData interface :
1. import [Link].*;
2. class Rsmd{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6. Connection con=[Link](
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. PreparedStatement ps=[Link]("select * from emp");
10. ResultSet rs=[Link]();
11. ResultSetMetaData rsmd=[Link]();
12.
13. [Link]("Total columns: "+[Link]());
14. [Link]("Column Name of 1st column: "+[Link](1))
;
15. [Link]("Column Type Name of 1st column: "+[Link]
eName(1));
16.
17. [Link]();
18. }catch(Exception e){ [Link](e);}
19. }
20. }
Output:
Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER
Java DatabaseMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database such as
database product name, database product version, driver name, name of total number of
tables, name of total number of views etc.
Commonly used methods of DatabaseMetaData interface
o public String getDriverName()throws SQLException: it returns the name
of the JDBC driver.
o public String getDriverVersion()throws SQLException: it returns the
version number of the JDBC driver.
o public String getUserName()throws SQLException: it returns the
username of the database.
o public String getDatabaseProductName()throws SQLException: it returns
the product name of the database.
o public String getDatabaseProductVersion()throws SQLException: it
returns the product version of the database.
o public ResultSet getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types)throws SQLException: it returns the
description of the tables of the specified catalog. The table type can be
TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
How to get the object of DatabaseMetaData:
The getMetaData() method of Connection interface returns the object of
DatabaseMetaData. Syntax:
1. public DatabaseMetaData getMetaData()throws SQLException
Simple Example of DatabaseMetaData interface :
1. import [Link].*;
2. class Dbmd{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6.
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. DatabaseMetaData dbmd=[Link]();
10.
11. [Link]("Driver Name: "+[Link]());
12. [Link]("Driver Version: "+[Link]());
13. [Link]("UserName: "+[Link]());
14. [Link]("Database Product Name: "+[Link]
me());
15. [Link]("Database Product Version: "+[Link]
ersion());
16.
17. [Link]();
18. }catch(Exception e){ [Link](e);}
19. }
20. }
Output:Driver Name: Oracle JDBC Driver
Driver Version: [Link].0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release [Link].0 -Production
download this example
Example of DatabaseMetaData interface that prints total number of
tables :
1. import [Link].*;
2. class Dbmd2{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6.
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. DatabaseMetaData dbmd=[Link]();
11. String table[]={"TABLE"};
12. ResultSet rs=[Link](null,null,null,table);
13.
14. while([Link]()){
15. [Link]([Link](3));
16. }
17.
18. [Link]();
19.
20. }catch(Exception e){ [Link](e);}
21.
22. }
23. }
download this example
Example of DatabaseMetaData interface that prints total number of
views :
1. import [Link].*;
2. class Dbmd3{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6.
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. DatabaseMetaData dbmd=[Link]();
11. String table[]={"VIEW"};
12. ResultSet rs=[Link](null,null,null,table);
13.
14. while([Link]()){
15. [Link]([Link](3));
16. }
17.
18. [Link]();
19.
20. }catch(Exception e){ [Link](e);}
21.
22. }
23. }
download this example
Next TopicStoring Image In Oracle Database
Example to store image in Oracle database
You can store images in the database in java by the help
of PreparedStatement interface.
The setBinaryStream() method of PreparedStatement is used to set Binary information
into the parameterIndex.
Signature of setBinaryStream method
The syntax of setBinaryStream() method is given below:
1. 1) public void setBinaryStream(int paramIndex,InputStream stream)
2. throws SQLException
3. 2) public void setBinaryStream(int paramIndex,InputStream stream,long len
gth)
4. throws SQLException
For storing image into the database, BLOB (Binary Large Object) datatype is used in the
table. For example:
1. CREATE TABLE "IMGTABLE"
2. ( "NAME" VARCHAR2(4000),
3. "PHOTO" BLOB
4. )
5. /
Let's write the jdbc code to store the image in the database. Here we are using d:\\[Link]
for the location of image. You can change it according to the image location.
Java Example to store image in the database
1. import [Link].*;
2. import [Link].*;
3. public class InsertImage {
4. public static void main(String[] args) {
5. try{
6. [Link]("[Link]");
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=[Link]("insert into imgtable values(?,?
)");
11. [Link](1,"sonoo");
12.
13. FileInputStream fin=new FileInputStream("d:\\[Link]");
14. [Link](2,fin,[Link]());
15. int i=[Link]();
16. [Link](i+" records affected");
17.
18. [Link]();
19. }catch (Exception e) {[Link]();}
20. }
21. }
If you see the table, record is stored in the database but image will not be shown. To do
so, you need to retrieve the image from the database which we are covering in the next
page.
download this example
Example to retrieve image from Oracle
database
By the help of PreparedStatement we can retrieve and store the image in the database.
The getBlob() method of PreparedStatement is used to get Binary information, it returns
the instance of Blob. After calling the getBytes() method on the blob object, we can get
the array of binary information that can be written into the image file.
Signature of getBlob() method of PreparedStatement
1. public Blob getBlob()throws SQLException
Signature of getBytes() method of Blob interface
1. public byte[] getBytes(long pos, int length)throws SQLException
We are assuming that image is stored in the imgtable.
1. CREATE TABLE "IMGTABLE"
2. ( "NAME" VARCHAR2(4000),
3. "PHOTO" BLOB
4. )
5. /
Now let's write the code to retrieve the image from the database and write it into the
directory so that it can be displayed.
In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be
displayed by the img tag.
1. import [Link].*;
2. import [Link].*;
3. public class RetrieveImage {
4. public static void main(String[] args) {
5. try{
6. [Link]("[Link]");
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=[Link]("select * from imgtable");
11. ResultSet rs=[Link]();
12. if([Link]()){//now on 1st row
13.
14. Blob b=[Link](2);//2 means 2nd column data
15. byte barr[]=[Link](1,(int)[Link]());//1 means first image
16.
17. FileOutputStream fout=new FileOutputStream("d:\\[Link]");
18. [Link](barr);
19.
20. [Link]();
21. }//end of if
22. [Link]("ok");
23.
24. [Link]();
25. }catch (Exception e) {[Link](); }
26. }
27. }
Now if you see the d drive, [Link] image is created.
download this example
Next TopicStoring file in the database using java
Example to store file in Oracle database:
The setCharacterStream() method of PreparedStatement is used to set character
information into the parameterIndex.
Syntax:
1) public void setBinaryStream(int paramIndex,InputStream stream)throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream stream,long length)throws SQLExceptio
For storing file into the database, CLOB (Character Large Object) datatype is used in the
table. For example:
1. CREATE TABLE "FILETABLE"
2. ( "ID" NUMBER,
3. "NAME" CLOB
4. )
5. /
Java Example to store file in database
1. import [Link].*;
2. import [Link].*;
3.
4. public class StoreFile {
5. public static void main(String[] args) {
6. try{
7. [Link]("[Link]");
8. Connection con=[Link](
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=[Link](
12. "insert into filetable values(?,?)");
13.
14. File f=new File("d:\\[Link]");
15. FileReader fr=new FileReader(f);
16.
17. [Link](1,101);
18. [Link](2,fr,(int)[Link]());
19. int i=[Link]();
20. [Link](i+" records affected");
21.
22. [Link]();
23.
24. }catch (Exception e) {[Link]();}
25. }
26. }
Example to retrieve file from Oracle database:
The getClob() method of PreparedStatement is used to get file information from the
database.
Syntax of getClob method
1. public Clob getClob(int columnIndex){}
Let's see the table structure of this example to retrieve the file.
1. CREATE TABLE "FILETABLE"
2. ( "ID" NUMBER,
3. "NAME" CLOB
4. )
5. /
The example to retrieve the file from the Oracle database is given below.
1. import [Link].*;
2. import [Link].*;
3.
4. public class RetrieveFile {
5. public static void main(String[] args) {
6. try{
7. [Link]("[Link]");
8. Connection con=[Link](
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=[Link]("select * from filetable");
12. ResultSet rs=[Link]();
13. [Link]();//now on 1st row
14.
15. Clob c=[Link](2);
16. Reader r=[Link]();
17.
18. FileWriter fw=new FileWriter("d:\\[Link]");
19.
20. int i;
21. while((i=[Link]())!=-1)
22. [Link]((char)i);
23.
24. [Link]();
25. [Link]();
26.
27. [Link]("success");
28. }catch (Exception e) {[Link](); }
29. }
30. }
Java CallableStatement Interface
CallableStatement interface is used to call the stored procedures and functions.
We can have business logic on the database by the use of stored procedures and
functions that will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may
create a function that receives date as the input and returns age of the employee as the
output.
What is the difference between stored procedures and functions.
The differences between stored procedures and functions are given below:
Stored Procedure Function
is used to perform business logic. is used to perform calcul
must not have the return type. must have the return type
may return 0 or more values. may return only one valu
We can call functions from the procedure. Procedure cannot be cal
Procedure supports input and output parameters. Function supports only in
Exception handling using try/catch block can be used in stored Exception handling usi
procedures. functions.
How to get the instance of CallableStatement?
The prepareCall() method of Connection interface returns the instance of
CallableStatement. Syntax is given below:
1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
The example to get the instance of CallableStatement is given below:
1. CallableStatement stmt=[Link]("{call myprocedure(?,?)}");
It calls the procedure myprocedure that receives 2 arguments.
Full example to call the stored procedure using
JDBC
To call the stored procedure, you need to create it in the database. Here, we are
assuming that stored procedure looks like this.
1. create or replace procedure "INSERTR"
2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user420 values(id,name);
7. end;
8. /
The table structure is given below:
1. create table user420(id number(10), name varchar2(200));
In this example, we are going to call the stored procedure INSERTR that receives id and
name as the parameter and inserts it into the table user420. Note that you need to
create the user420 table as well to run this application.
1. import [Link].*;
2. public class Proc {
3. public static void main(String[] args) throws Exception{
4.
5. [Link]("[Link]");
6. Connection con=[Link](
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. CallableStatement stmt=[Link]("{call insertR(?,?)}");
10. [Link](1,1011);
11. [Link](2,"Amit");
12. [Link]();
13.
14. [Link]("success");
15. }
16. }
Now check the table in the database, value is inserted in the user420 table.
Example to call the function using JDBC
In this example, we are calling the sum4 function that receives two input and returns the
sum of the given number. Here, we have used the registerOutParameter method of
CallableStatement interface, that registers the output parameter with its corresponding
type. It provides information to the CallableStatement about the type of result being
displayed.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT,
DOUBLE, BLOB, CLOB etc.
Let's create the simple function in the database first.
1. create or replace function sum4
2. (n1 in number,n2 in number)
3. return number
4. is
5. temp number(8);
6. begin
7. temp :=n1+n2;
8. return temp;
9. end;
10. /
Now, let's write the simple program to call the function.
1. import [Link].*;
2.
3. public class FuncSum {
4. public static void main(String[] args) throws Exception{
5.
6. [Link]("[Link]");
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. CallableStatement stmt=[Link]("{?= call sum4(?,?)}");
11. [Link](2,10);
12. [Link](3,43);
13. [Link](1,[Link]);
14. [Link]();
15.
16. [Link]([Link](1));
17.
18. }
19. }
Output: 53
Transaction Management in JDBC
Transaction represents a single unit of work.
The ACID properties describes the transaction management well. ACID stands for
Atomicity, Consistency, isolation and durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another
consistent state.
Backward Skip 10sPlay VideoForward Skip 10s
Skip ad
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the
event of errors, power loss etc.
Advantage of Transaction Mangaement
fast performance It makes the performance fast because database is hit at the time of
commit.
In JDBC, Connection interface provides methods to manage transaction.
Method Description
void setAutoCommit(boolean status) It is true bydefault means e
void commit() commits the transaction.
void rollback() cancels the transaction.
Simple example of transaction management in
jdbc using Statement
Let's see the simple example of transaction management using Statement.
1. import [Link].*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. [Link]("[Link]");
5. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe"
,"system","oracle");
6. [Link](false);
7.
8. Statement stmt=[Link]();
9. [Link]("insert into user420 values(190,'abhi',40000)");
10. [Link]("insert into user420 values(191,'umesh',50000)");
11.
12. [Link]();
13. [Link]();
14. }}
If you see the table emp400, you will see that 2 records has been added.
Example of transaction management in jdbc
using PreparedStatement
Let's see the simple example of transaction management using PreparedStatement.
1. import [Link].*;
2. import [Link].*;
3. class TM{
4. public static void main(String args[]){
5. try{
6.
7. [Link]("[Link]");
8. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe"
,"system","oracle");
9. [Link](false);
10.
11. PreparedStatement ps=[Link]("insert into user420 values(?,?,?)");
12.
13. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
14. while(true){
15.
16. [Link]("enter id");
17. String s1=[Link]();
18. int id=[Link](s1);
19.
20. [Link]("enter name");
21. String name=[Link]();
22.
23. [Link]("enter salary");
24. String s3=[Link]();
25. int salary=[Link](s3);
26.
27. [Link](1,id);
28. [Link](2,name);
29. [Link](3,salary);
30. [Link]();
31.
32. [Link]("commit/rollback");
33. String answer=[Link]();
34. if([Link]("commit")){
35. [Link]();
36. }
37. if([Link]("rollback")){
38. [Link]();
39. }
40.
41.
42. [Link]("Want to add more records y/n");
43. String ans=[Link]();
44. if([Link]("n")){
45. break;
46. }
47.
48. }
49. [Link]();
50. [Link]("record successfully saved");
51.
52. [Link]();//before closing connection commit() is called
53. }catch(Exception e){[Link](e);}
54.
55. }}
It will ask to add more records until you press n. If you press n, transaction is committed.
Next Batch Processing in JDBC
Instead of executing a single query, we can execute a batch (group) of queries. It makes
the performance fast. It is because when one sends multiple statements of SQL at once
to the database, the communication overhead is reduced significantly, as one is not
communicating with the database frequently, which in turn results to fast performance.
The [Link] and [Link] interfaces provide methods for
batch processing.
Advantage of Batch Processing
Fast Performance
Methods of Statement interface
The required methods for batch processing are given below:
Backward Skip 10sPlay VideoForward Skip 10s
Method Description
The addBatch(String
void addBatch(String query) PreparedStatement, and
batch.
The executeBatch() me
together statements. The
int[] executeBatch()
the element of the array
update statement.
boolean [Link]() throws If the target database fa
SQLException method returns true.
The method removes al
void clearBatch()
addBatch() method.
Example of batch processing in JDBC
Let's see the simple example of batch processing in JDBC. It follows following steps:
o Load the driver class
o Create Connection
o Create Statement
o Add query in the batch
o Execute Batch
o Close Connection
FileName: [Link]
1. import [Link].*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. [Link]("[Link]");
5. Connection con=[Link]("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");
6. [Link](false);
7.
8. Statement stmt=[Link]();
9. [Link]("insert into user420 values(190,'abhi',40000)");
10. [Link]("insert into user420 values(191,'umesh',50000)");
11.
12. [Link]();//executing the batch
13.
14. [Link]();
15. [Link]();
16. }}
If you see the table user420, two records have been added.
Example of batch processing using PreparedStatement
FileName: [Link]
1. import [Link].*;
2. import [Link].*;
3. class BP{
4. public static void main(String args[]){
5. try{
6.
7. [Link]("[Link]");
8. Connection con=[Link]("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");
9.
10. PreparedStatement ps=[Link]("insert into user420 values(?,?,
?)");
11.
12. BufferedReader br=new BufferedReader(new InputStreamReader([Link])
);
13. while(true){
14.
15. [Link]("enter id");
16. String s1=[Link]();
17. int id=[Link](s1);
18.
19. [Link]("enter name");
20. String name=[Link]();
21.
22. [Link]("enter salary");
23. String s3=[Link]();
24. int salary=[Link](s3);
25.
26. [Link](1,id);
27. [Link](2,name);
28. [Link](3,salary);
29.
30. [Link]();
31. [Link]("Want to add more records y/n");
32. String ans=[Link]();
33. if([Link]("n")){
34. break;
35. }
36.
37. }
38. [Link]();// for executing the batch
39.
40. [Link]("record successfully saved");
41.
42. [Link]();
43. }catch(Exception e){[Link](e);}
44.
45. }}
Output:
enter id
101
enter name
Manoj Kumar
enter salary
10000
Want to add more records y/n
y
enter id
101
enter name
Harish Singh
enter salary
15000
Want to add more records y/n
y
enter id
103
enter name
Rohit Anuragi
enter salary
30000
Want to add more records y/n
y
enter id
104
enter name
Amrit Gautam
enter salary
40000
Want to add more records y/n
n
record successfully saved
It will add the queries into the batch until user press n. Finally, it executes the batch.
Thus, all the added queries will be fired.
Next TopicJDBC RowSet
← prevnext →
JDBC RowSet
An instance of RowSet is the Java bean component because it has properties and Java
bean notification mechanism. It is the wrapper of ResultSet. A JDBC RowSet facilitates a
mechanism to keep the data in tabular form. It happens to make the data more flexible
as well as easier as compared to a ResultSet. The connection between the data source
and the RowSet object is maintained throughout its life cycle. The RowSet supports
development models that are component-based such as JavaBeans, with the standard
set of properties and the mechanism of event notification.
It was in the JDBC 2.0, the support for the RowSet was introduced using the optional
packages. But the implementations were standardized for RowSet in the JDBC RowSet
Implementations Specification (JSR-114) by the Sun Microsystems that is being present
in the JDK (Java Development Kit) 5.0.
The implementation classes of the RowSet interface are as follows:
o JdbcRowSet
o CachedRowSet
o WebRowSet
o JoinRowSet
o FilteredRowSet
Let's see how to create and execute RowSet.
Backward Skip 10sPlay VideoForward Skip 10s
You can skip to video in 3
1. JdbcRowSet rowSet = [Link]().createJdbcRowSet();
2. [Link]("jdbc:oracle:thin:@localhost:1521:xe");
3. [Link]("system");
4. [Link]("oracle");
5.
6. [Link]("select * from emp400");
7. [Link]();
It is the new way to get the instance of JdbcRowSet since JDK 7.
Advantage of RowSet
The advantages of using RowSet are given below:
1. It is easy and flexible to use.
2. It is Scrollable and Updatable by default.
Example of JdbcRowSet
Let's see the simple example of JdbcRowSet without event handling code.
FileName: [Link]
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. [Link]("[Link]");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = [Link]().createJdbcRowSet();
16. [Link]("jdbc:oracle:thin:@localhost:1521:xe");
17. [Link]("system");
18. [Link]("oracle");
19.
20. [Link]("select * from emp400");
21. [Link]();
22.
23. while ([Link]()) {
24. // Generating cursor Moved event
25. [Link]("Id: " + [Link](1));
26. [Link]("Name: " + [Link](2));
27. [Link]("Salary: " + [Link](3));
28. }
29.
30. }
31. }
The output is given below:
Id: 55
Name: Om Bhim
Salary: 70000
Id: 190
Name: abhi
Salary: 40000
Id: 191
Name: umesh
Salary: 50000
Example of JDBC RowSet with Event Handling
To perform event handling with JdbcRowSet, you need to add the instance
of RowSetListener in the addRowSetListener method of JdbcRowSet.
The RowSetListener interface provides 3 method that must be implemented. They are
as follows:
1. public void cursorMoved(RowSetEvent event);
2. public void rowChanged(RowSetEvent event);
3. public void rowSetChanged(RowSetEvent event);
Let's write the code to retrieve the data and perform some additional tasks while the
cursor is moved, the cursor is changed, or the rowset is changed. The event handling
operation can't be performed using ResultSet, so it is preferred now.
FileName: [Link]
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. [Link]("[Link]");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = [Link]().createJdbcRowSet();
16. [Link]("jdbc:oracle:thin:@localhost:1521:xe");
17. [Link]("system");
18. [Link]("oracle");
19.
20. [Link]("select * from emp400");
21. [Link]();
22.
23. //Adding Listener and moving RowSet
24. [Link](new MyListener());
25.
26. while ([Link]()) {
27. // Generating cursor Moved event
28. [Link]("Id: " + [Link](1));
29. [Link]("Name: " + [Link](2));
30. [Link]("Salary: " + [Link](3));
31. }
32.
33. }
34. }
35.
36. class MyListener implements RowSetListener {
37. public void cursorMoved(RowSetEvent event) {
38. [Link]("Cursor Moved...");
39. }
40. public void rowChanged(RowSetEvent event) {
41. [Link]("Cursor Changed...");
42. }
43. public void rowSetChanged(RowSetEvent event) {
44. [Link]("RowSet changed...");
45. }
46. }
The output is as follows:
Cursor Moved...
Id: 55
Name: Om Bhim
Salary: 70000
Cursor Moved...
Id: 190
Name: abhi
Salary: 40000
Cursor Moved...
Id: 191
Name: umesh
Salary: 50000
Cursor Moved...
Next TopicJDBC New Features
← prevnext →
[Link]
Java Database Connectivity with 5 Steps
1. 5 Steps to connect to the database in java
1. Register the driver class
2. Create the connection object
3. Create the Statement object
4. Execute the query
5. Close the connection object
There are 5 steps to connect any java application with the database using JDBC. These steps are as follows
Register the Driver class
Create connection
Create statement
Execute queries
Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to dynamically
Syntax of forName() method
1. public static void forName(String className)throws ClassNotFoundException
Note: Since JDBC 4.0, explicitly registering the driver is optional. We
just need to put vender's Jar in the classpath, and then JDBC driver
manager can detect and load the driver automatically.
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
1. [Link]("[Link]");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax of getConnection() method
1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException
Example to establish connection with the Oracle
database
1. Connection con=[Link](
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of statement
Syntax of createStatement() method
1. public Statement createStatement()throws SQLException
Example to create the statement object
1. Statement stmt=[Link]();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database. This method
all the records of a table.
Syntax of executeQuery() method
1. public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
1. ResultSet rs=[Link]("select * from emp");
2.
3. while([Link]()){
4. [Link]([Link](1)+" "+[Link](2));
5. }
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The close() method of Co
Syntax of close() method
1. public void close()throws SQLException
Example to close connection
Advertisement
1. [Link]();
Note: Since Java 7, JDBC has ability to use try-with-resources
statement to automatically close resources of type Connection,
ResultSet, and Statement.
It avoids explicit connection closing step.
Java Database Connectivity MCQ
1. What is the first step to connect to a database in Java?
1. Load the JDBC driver
2. Create a connection
3. Execute a query
4. Close the connection
Show Answer Workspace
2. Which method is used to establish a connection to the database?
1. [Link]()
2. [Link]()
3. [Link]()
4. [Link]()
Show Answer Workspace
3. What must be done after executing a query to avoid memory leaks?
1. Close the Statement object
2. Close the ResultSet object
3. Close the Connection object
4. All of the above
Show Answer Workspace
4. Which interface provides the methods to execute SQL queries?
1. Connection
2. Statement
3. DriverManager
4. ResultSet
Show Answer Workspace
5. How do you handle SQL exceptions in JDBC?
1. Using try-catch blocks
2. Using if-else statements
3. Using a switch statement
4. Using for loops
Java Database Connectivity with Oracle
To connect java application with the oracle database, we need to follow 5 following steps. In this ex
So we need to know following information for the oracle database:
1. Driver class: The driver class for the oracle database is [Link].
2. Connection URL: The connection URL for the oracle10G database is jdbc:oracle:thin:@loca
database, thin is the driver, localhost is the server name on which oracle is running, we may also
the Oracle service name. You may get all these information from the [Link] file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle database.
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQL qu
1. create table emp(id number(10),name varchar2(40),age number(3));
Example to Connect Java Application with Oracle
database
In this example, we are connecting to an Oracle database and getting data
from emp table. Here, system and oracle are the username and password of the
Oracle database.
1. import [Link].*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. [Link]("[Link]");
7.
8. //step2 create the connection object
9. Connection con=[Link](
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=[Link]();
14.
15. //step4 execute query
16. ResultSet rs=[Link]("select * from emp");
17. while([Link]())
18. [Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
19.
20. //step5 close the connection object
21. [Link]();
22.
23. }catch(Exception e){ [Link](e);}
24.
25. }
26. }
download this example
The above example will fetch all the records of emp table.
To connect java application with the Oracle database [Link] file is required to be
loaded.
download the jar file [Link]
Two ways to load the jar file:
1. paste the [Link] file in jre/lib/ext folder
2. set classpath
1) paste the [Link] file in JRE/lib/ext folder:
Firstly, search the [Link] file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:
temporary
permanent
How to set the temporary classpath:
Firstly, search the [Link] file then open command prompt and write:
1. C:>set classpath=c:\folder\[Link];.;
How to set the permanent classpath:
Go to environment variable then click on new tab. In variable name write classpath and
in variable value paste the path to [Link] by appending [Link];.; as C:\
oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\[Link];.;
Java Database Connectivity with MySQL
To connect Java application with the MySQL database, we need to follow 5 following
steps.
In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
1. Driver class: The driver class for the mysql database is [Link].
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the
database, localhost is the server name on which mysql is running, we may also
use IP address, 3306 is the port number and sonoo is the database name. We
may use any database, in such case, we need to replace the sonoo with our
database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to
create database first.
1. create database sonoo;
2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));
Example to Connect Java Application with mysql
database
In this example, sonoo is the database name, root is the username and password both.
1. import [Link].*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6. Connection con=[Link](
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=[Link]();
10. ResultSet rs=[Link]("select * from emp");
11. while([Link]())
12. [Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
13. [Link]();
14. }catch(Exception e){ [Link](e);}
15. }
16. }
download this example
The above example will fetch all the records of emp table.
To connect java application with the mysql database, [Link] file is
required to be loaded.
download the jar file [Link]
Two ways to load the jar file:
1. Paste the [Link] file in jre/lib/ext folder
2. Set classpath
1) Paste the [Link] file in JRE/lib/ext folder:
Download the [Link] file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath:
There are two ways to set the classpath:
temporary
permanent
How to set the temporary classpath
open command prompt and write:
1. C:>set classpath=c:\folder\[Link];.;
How to set the permanent classpath
Go to environment variable then click on new tab. In variable name write classpath and
in variable value paste the path to the [Link] file by appending
[Link];.; as C:\folder\[Link];.;
Java Database Connectivity with MySQL MCQ
1. Which driver class is used to connect to a MySQL database in Java?
1. [Link]
2. [Link]
3. [Link]
4. [Link]
Show Answer Workspace
2. Which method is used to establish a connection to the database?
1. [Link]()
2. [Link]()
3. [Link]()
4. [Link]()
Show Answer Workspace
3. Which of the following is the correct URL to connect to a MySQL database
named 'testdb'?
1. jdbc:mysql://localhost:3306/testdb
2. jdbc:mysql://localhost/testdb
3. mysql://localhost:3306/testdb
4. jdbc:mysql:localhost:3306/testdb
Show Answer Workspace
4. What is the role of the Statement interface in JDBC?
1. To execute SQL queries
2. To establish a database connection
3. To close the database connection
4. To load the database driver
Show Answer Workspace
5. Which method is used to execute a SELECT query in JDBC?
1. executeQuery()
2. execute()
3. executeUpdate()
4. runQuery()
Show Answer Workspace
Accessing a Microsoft Access database without using a Data Source Name (DSN)
is often preferred in scenarios where portability, simplicity, or avoiding system-level
configuration is essential. It can be achieved through a DSN-less connection, which
allows a Java program to directly specify the connection parameters, bypassing the
need for a pre-configured DSN.
In Java, connectivity with a Microsoft Access database is typically done using the JDBC-
ODBC Bridge or a third-party library like UCanAccess. As the JDBC-ODBC bridge has
been deprecated in newer versions of Java, UCanAccess is a popular alternative that
offers robust support for Access databases.
Key Components of DSN-less Connection
1. Driver Specification: A JDBC driver must be specified explicitly. For Access
databases, the UCanAccess JDBC driver is commonly used.
2. Database Path: The absolute or relative file path to the Access database file
(.mdb or .accdb) is directly provided in the connection URL.
3. Dependencies: UCanAccess requires certain libraries ([Link],
[Link], etc.) to be included in the project.
4. Connection URL Format: The connection URL includes the database file path
and optional configurations.
Advantages of DSN-less Connection
1. Portability: No need for DSN configuration on every system where the
application runs.
2. Ease of Setup: Eliminates reliance on administrative tools or registry settings for
configuration.
3. Dynamic Connections: Database paths can be easily changed
programmatically.
Example of DSN-less Connection Using Java and UCanAccess
Database File: [Link]
ID Name
1 Alice
2 Bob
3 Charlie
File Name: [Link]
Backward Skip 10sPlay VideoForward Skip 10s
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. public class AccessDatabaseConnection {
6. public static void main(String[] args) {
7. // Path to the Microsoft Access database file
8. String dbFilePath = "C:/databases/[Link]";
9. // Connection URL for UCanAccess driver
10. String jdbcURL = "jdbc:ucanaccess://" + dbFilePath;
11. // Database operations
12. try (Connection connection = [Link](jdbcURL)) {
13. [Link]("Connection established successfully.");
14. // Create a statement
15. Statement statement = [Link]();
16. // Execute a query to retrieve data from Employees table
17. String query = "SELECT ID, Name FROM Employees";
18. ResultSet resultSet = [Link](query);
19. // Process the result set
20. [Link]("Employee Details:");
21. while ([Link]()) {
22. [Link]("ID: " + [Link]("ID"));
23. [Link]("Name: " + [Link]("Name"));
24. }
25. // Close resources
26. [Link]();
27. [Link]();
28. } catch (Exception e) {
29. [Link]();
30. }
31. }
32. }
Output:
Connection established successfully.
Employee Details:
ID: 1
Name: Alice
ID: 2
Name: Bob
ID: 3
Name: Charlie
Explanation
The provided code demonstrates a simple way to connect to an Access database file
without using a DSN. It starts by specifying the file path of the database, which is directly
embedded into the JDBC URL.
The UCanAccess JDBC driver is used to establish the connection. After successfully
connecting, the program executes an SQL query on a specified table, retrieves the
results, and prints them to the console. The try-with-resources statement ensures that
the database connection is closed automatically, avoiding potential memory leaks.
This approach minimizes external dependencies and makes the application
configuration-free for database connectivity.
Steps to Set Up and Run the Code
1. Download UCanAccess:
o Visit the official [UCanAccess]([Link] website.
o Download the latest version of the UCanAccess library.
2. Add Dependencies
Include the following JAR files in your project:
o [Link]
o [Link]
o [Link]
o [Link]
o [Link]
Note: If using an IDE like Eclipse or IntelliJ, add these files to the
project's build path.
3. Prepare the Database
Ensure the .accdb or .mdb file exists and has a valid schema (tables, columns, etc.).
4. Run the Program
o Compile and execute the Java program.
o Ensure the file path to the Access database is correct.
o Check the console output for query results or connection issues.
UCanAccess Features and Configuration Options
o Read/Write Operations: UCanAccess supports all common SQL operations, such
as SELECT, INSERT, UPDATE, and DELETE.
o Data Integrity: Handles data types, constraints, and relationships defined in the
Access database.
o Encryption Support: It can connect to password-protected Access databases by
appending ;jackcessOpener=YourOpenerClass to the connection URL.
o Logging: It supports detailed logging of SQL queries and transactions.
Customizing the Connection URL
The connection URL can be customized for various purposes:
1. Read-Only Mode
1. String jdbcURL = "jdbc:ucanaccess://" + dbFilePath + ";openExclusive=true";
It ensures no other application can access the database simultaneously.
2. Password-Protected Database
1. String jdbcURL = "jdbc:ucanaccess://" + dbFilePath + ";jackcessOpener=YourOpener
Class";
Replace YourOpenerClass with the appropriate handler for decrypting the database.
3. Memory Settings
1. Add ;memory=true to improve performance for in-memory operations.
Best Practices for DSN-less Connections
1. Use Relative Paths: For portability, use relative file paths instead of hardcoded
absolute paths.
String dbFilePath = "./data/[Link]";
2. Error Handling: Implement detailed error logging to identify issues during
connection or query execution.
3. Connection Pooling: For high-performance applications, integrate a connection
pooling library to manage database connections efficiently.
4. Thread Safety: Ensure thread-safe operations when accessing the database
concurrently.
Conclusion
Connecting to an Access database without a DSN is straightforward and provides
flexibility for Java applications. The UCanAccess library simplifies this process by
offering a robust JDBC driver with extensive functionality.
By avoiding DSN configurations, developers can achieve greater portability and reduced
setup complexity, making this approach ideal for lightweight and easily deployable
solutions.
DriverManager class
The DriverManager class is the component of JDBC API and also a member of
the [Link] package. The DriverManager class acts as an interface between users and
drivers. It keeps track of the drivers that are available and handles establishing a
connection between a database and the appropriate driver. It contains all the appropriate
methods to register and deregister the database driver class and to create a connection
between a Java application and the database. The DriverManager class maintains a list
of Driver classes that have registered themselves by calling the method
[Link](). Note that before interacting with a Database, it is a
mandatory process to register the driver; otherwise, an exception is thrown.
Methods of the DriverManager Class
Method Description
is used to register the given driver with
1) public static synchronized void DriverManager. No action is performed by the
registerDriver(Driver driver): method when the given driver is already
registered.
is used to deregister the given driver (drop the
2) public static synchronized void driver from the list) with DriverManager. If the
deregisterDriver(Driver driver): given driver has been removed from the list,
then no action is performed by the method.
is used to establish the connection with the
3) public static Connection specified url. The SQLException is thrown
getConnection(String url) throws when the corresponding Driver class of the
SQLException: given database is not registered with the
DriverManager.
4) public static Connection is used to establish the connection with the
getConnection(String url,String specified url, username, and password. The
userName,String password) throws SQLException is thrown when the
SQLException: corresponding Driver class of the given
database is not registered with the
DriverManager.
Those drivers that understand the mentioned
URL (present in the parameter of the method)
5) public static Driver getDriver(String url) are returned by this method provided those
drivers are mentioned in the list of registered
drivers.
The duration of time a driver is allowed to wait
6) pubic static int getLoginTimeout() in order to establish a connection with the
database is returned by this method.
The method provides the time in seconds. sec
mentioned in the parameter is the maximum
time that a driver is allowed to wait in order to
7) pubic static void setLoginTimeout(int
establish a connection with the database. If 0
sec)
is passed in the parameter of this method, the
driver will have to wait infinitely while trying to
establish the connection with the database.
A connection object is returned by this method
after creating a connection to the database
present at the mentioned URL, which is the
first parameter of this method. The second
parameter, which is "prop", fetches the
8) public static Connection
authentication details of the database
getConnection(String URL, Properties
(username and password.). Similar to the
prop) throws SQLException
other variation of the getConnection() method,
this method also throws the SQLException,
when the corresponding Driver class of the
given database is not registered with the
DriverManager.
Connection interface
A Connection is a session between a Java application and a database. It helps to
establish a connection with the database.
The Connection interface is a factory of Statement, PreparedStatement, and
DatabaseMetaData, i.e., an object of Connection can be used to get the object of
Statement and DatabaseMetaData. The Connection interface provide many methods for
transaction management like commit(), rollback(), setAutoCommit(),
setTransactionIsolation(), etc.
By default, connection commits the changes after executing queries.
Commonly used methods of Connection interface:
1) public Statement createStatement(): creates a statement object that can be used to
execute SQL queries.
2) public Statement createStatement(int resultSetType,int
resultSetConcurrency): Creates a Statement object that will generate ResultSet
objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status. By
default, it is true.
4) public void commit(): saves the changes made since the previous commit/rollback is
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources
immediately.
Connection Interface Fields
There are some common Connection interface constant fields that are present in the
Connect interface. These fields specify the isolation level of a transaction.
TRANSACTION_NONE: No transaction is supported, and it is indicated by this constant.
TRANSACTION_READ_COMMITTED: It is a constant which shows that the dirty reads
are not allowed. However, phantom reads and non-repeatable reads can occur.
TRANSACTION_READ_UNCOMMITTED: It is a constant which shows that dirty reads,
non-repeatable reads, and phantom reads can occur.
TRANSACTION_REPEATABLE_READ: It is a constant which shows that the non-
repeatable reads and dirty reads are not allowed. However, phantom reads and can
occur.
TRANSACTION_SERIALIZABLE: It is a constant which shows that the non-repeatable
reads, dirty reads as well as the phantom reads are not allowed.
Statement interface
The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the
object of ResultSet.
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It
returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be
create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return
multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
Example of Statement interface
Let’s see the simple example of Statement interface to insert, update and delete the
record.
1. import [Link].*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4. [Link]("[Link]");
5. Connection con=[Link]("jdbc:oracle:thin:@localhost:1
521:xe","system","oracle");
6. Statement stmt=[Link]();
7.
8. //[Link]("insert into emp765 values(33,'Irfan',50000)");
9. //int result=[Link]("update emp765 set name='Vimal',salary=100
00 where id=33");
10. int result=[Link]("delete from emp765 where id=33");
11. [Link](result+" records affected");
12. [Link]();
13. }}
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.
By default, ResultSet object can be moved forward only and it is not
updatable.
But we can make this object to move forward and backward direction by passing either
TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in
createStatement(int,int) method as well as we can make this object as updatable by:
1. Statement stmt = [Link](ResultSet.TYPE_SCROLL_INSENSITIVE,
2. ResultSet.CONCUR_UPDATABLE);
Commonly used methods of ResultSet interface
is used to move the cursor to the one row
1) public boolean next():
next from the current position.
is used to move the cursor to the one row
2) public boolean previous():
previous from the current position.
is used to move the cursor to the first row in
3) public boolean first():
result set object.
4) public boolean last(): is used to move the cursor to the last row in
result set object.
is used to move the cursor to the specified
5) public boolean absolute(int row):
row number in the ResultSet object.
is used to move the cursor to the relative row
6) public boolean relative(int row): number in the ResultSet object, it may be
positive or negative.
is used to return the data of specified column
7) public int getInt(int columnIndex):
index of the current row as int.
is used to return the data of specified column
8) public int getInt(String columnName):
name of the current row as int.
9) public String getString(int is used to return the data of specified column
columnIndex): index of the current row as String.
10) public String getString(String is used to return the data of specified column
columnName): name of the current row as String.
Example of Scrollable ResultSet
Let’s see the simple example of ResultSet interface to retrieve the data of 3rd row.
1. import [Link].*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4.
5. [Link]("[Link]");
6. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe"
,"system","oracle");
7. Statement stmt=[Link](ResultSet.TYPE_SCROLL_SENSITIVE,Result
Set.CONCUR_UPDATABLE);
8. ResultSet rs=[Link]("select * from emp765");
9.
10. //getting the record of 3rd row
11. [Link](3);
12. [Link]([Link](1)+" "+[Link](2)+" "+[Link](3));
13.
14. [Link]();
15. }}
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.
Let's see the example of parameterized query:
1. String sql="insert into emp values(?,?,?)";
As you can see, we are passing parameter (?) for the values. Its value will be set by
calling the setter methods of PreparedStatement.
Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
How to get the instance of PreparedStatement?
The prepareStatement() method of Connection interface is used to return the object of
PreparedStatement. Syntax:
1. public PreparedStatement prepareStatement(String query)throws SQLException{}
Methods of PreparedStatement interface
The important methods of PreparedStatement interface are given below:
Method Description
public void setInt(int paramIndex, int value) sets the integer value to th
public void setString(int paramIndex, String value) sets the String value to the
public void setFloat(int paramIndex, float value) sets the float value to the g
public void setDouble(int paramIndex, double value) sets the double value to th
public int executeUpdate() executes the query. It is us
public ResultSet executeQuery() executes the select query.
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:
1. import [Link].*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6.
7. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe"
,"system","oracle");
8.
9. PreparedStatement stmt=[Link]("insert into Emp values(?,?)");
10. [Link](1,101);//1 specifies the first parameter in the query
11. [Link](2,"Ratan");
12.
13. int i=[Link]();
14. [Link](i+" records inserted");
15.
16. [Link]();
17.
18. }catch(Exception e){ [Link](e);}
19.
20. }
21. }
download this example
Example of PreparedStatement interface that updates the record
1. PreparedStatement stmt=[Link]("update emp set name=? where id=
?");
2. [Link](1,"Sonoo");//1 specifies the first parameter in the query i.e. name
3. [Link](2,101);
4.
5. int i=[Link]();
6. [Link](i+" records updated");
download this example
Example of PreparedStatement interface that deletes the record
1. PreparedStatement stmt=[Link]("delete from emp where id=?");
2. [Link](1,101);
3.
4. int i=[Link]();
5. [Link](i+" records deleted");
download this example
Example of PreparedStatement interface that retrieve the records of
a table
1. PreparedStatement stmt=[Link]("select * from emp");
2. ResultSet rs=[Link]();
3. while([Link]()){
4. [Link]([Link](1)+" "+[Link](2));
5. }
download this example
Example of PreparedStatement to insert records until user press n
1. import [Link].*;
2. import [Link].*;
3. class RS{
4. public static void main(String args[])throws Exception{
5. [Link]("[Link]");
6. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe"
,"system","oracle");
7.
8. PreparedStatement ps=[Link]("insert into emp130 values(?,?,?)");
9.
10. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
11.
12. do{
13. [Link]("enter id:");
14. int id=[Link]([Link]());
15. [Link]("enter name:");
16. String name=[Link]();
17. [Link]("enter salary:");
18. float salary=[Link]([Link]());
19.
20. [Link](1,id);
21. [Link](2,name);
22. [Link](3,salary);
23. int i=[Link]();
24. [Link](i+" records affected");
25.
26. [Link]("Do you want to continue: y/n");
27. String s=[Link]();
28. if([Link]("n")){
29. break;
30. }
31. }while(true);
32.
33. [Link]();
34. }}
Java ResultSetMetaData Interface
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column
type etc. , ResultSetMetaData interface is useful because it provides methods to get
metadata from the ResultSet object.
Commonly Used Methods Of Resultsetmetadata Interface
Method Description
public int getColumnCount()throws SQLException It returns the total numbe
public String getColumnName(int index)throws SQLException It returns the column nam
public String getColumnTypeName(int index)throws SQLException It returns the column typ
public String getTableName(int index)throws SQLException It returns the table name
How to get the object of ResultSetMetaData:
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax:
1. public ResultSetMetaData getMetaData()throws SQLException
Example of ResultSetMetaData interface :
1. import [Link].*;
2. class Rsmd{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6. Connection con=[Link](
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. PreparedStatement ps=[Link]("select * from emp");
10. ResultSet rs=[Link]();
11. ResultSetMetaData rsmd=[Link]();
12.
13. [Link]("Total columns: "+[Link]());
14. [Link]("Column Name of 1st column: "+[Link](1))
;
15. [Link]("Column Type Name of 1st column: "+[Link]
eName(1));
16.
17. [Link]();
18. }catch(Exception e){ [Link](e);}
19. }
20. }
Output:
Total columns: 2
Column Name of 1st column: ID
Column Type Name of 1st column: NUMBER
Java DatabaseMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database such as
database product name, database product version, driver name, name of total number of
tables, name of total number of views etc.
Commonly used methods of DatabaseMetaData interface
o public String getDriverName()throws SQLException: it returns the name
of the JDBC driver.
o public String getDriverVersion()throws SQLException: it returns the
version number of the JDBC driver.
o public String getUserName()throws SQLException: it returns the
username of the database.
o public String getDatabaseProductName()throws SQLException: it returns
the product name of the database.
o public String getDatabaseProductVersion()throws SQLException: it
returns the product version of the database.
o public ResultSet getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types)throws SQLException: it returns the
description of the tables of the specified catalog. The table type can be
TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
How to get the object of DatabaseMetaData:
The getMetaData() method of Connection interface returns the object of
DatabaseMetaData. Syntax:
1. public DatabaseMetaData getMetaData()throws SQLException
Simple Example of DatabaseMetaData interface :
1. import [Link].*;
2. class Dbmd{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6.
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. DatabaseMetaData dbmd=[Link]();
10.
11. [Link]("Driver Name: "+[Link]());
12. [Link]("Driver Version: "+[Link]());
13. [Link]("UserName: "+[Link]());
14. [Link]("Database Product Name: "+[Link]
me());
15. [Link]("Database Product Version: "+[Link]
ersion());
16.
17. [Link]();
18. }catch(Exception e){ [Link](e);}
19. }
20. }
Output:Driver Name: Oracle JDBC Driver
Driver Version: [Link].0XE
Database Product Name: Oracle
Database Product Version: Oracle Database 10g Express Edition
Release [Link].0 -Production
download this example
Example of DatabaseMetaData interface that prints total number of
tables :
1. import [Link].*;
2. class Dbmd2{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6.
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. DatabaseMetaData dbmd=[Link]();
11. String table[]={"TABLE"};
12. ResultSet rs=[Link](null,null,null,table);
13.
14. while([Link]()){
15. [Link]([Link](3));
16. }
17.
18. [Link]();
19.
20. }catch(Exception e){ [Link](e);}
21.
22. }
23. }
download this example
Example of DatabaseMetaData interface that prints total number of
views :
1. import [Link].*;
2. class Dbmd3{
3. public static void main(String args[]){
4. try{
5. [Link]("[Link]");
6.
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. DatabaseMetaData dbmd=[Link]();
11. String table[]={"VIEW"};
12. ResultSet rs=[Link](null,null,null,table);
13.
14. while([Link]()){
15. [Link]([Link](3));
16. }
17.
18. [Link]();
19.
20. }catch(Exception e){ [Link](e);}
21.
22. }
23. }
Example to store image in Oracle database
You can store images in the database in java by the help
of PreparedStatement interface.
The setBinaryStream() method of PreparedStatement is used to set Binary information
into the parameterIndex.
Signature of setBinaryStream method
The syntax of setBinaryStream() method is given below:
1. 1) public void setBinaryStream(int paramIndex,InputStream stream)
2. throws SQLException
3. 2) public void setBinaryStream(int paramIndex,InputStream stream,long len
gth)
4. throws SQLException
For storing image into the database, BLOB (Binary Large Object) datatype is used in the
table. For example:
Backward Skip 10sPlay VideoForward Skip 10s
1. CREATE TABLE "IMGTABLE"
2. ( "NAME" VARCHAR2(4000),
3. "PHOTO" BLOB
4. )
5. /
Let's write the jdbc code to store the image in the database. Here we are using d:\\[Link]
for the location of image. You can change it according to the image location.
Java Example to store image in the database
1. import [Link].*;
2. import [Link].*;
3. public class InsertImage {
4. public static void main(String[] args) {
5. try{
6. [Link]("[Link]");
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=[Link]("insert into imgtable values(?,?
)");
11. [Link](1,"sonoo");
12.
13. FileInputStream fin=new FileInputStream("d:\\[Link]");
14. [Link](2,fin,[Link]());
15. int i=[Link]();
16. [Link](i+" records affected");
17.
18. [Link]();
19. }catch (Exception e) {[Link]();}
20. }
21. }
If you see the table, record is stored in the database but image will not be shown. To do
so, you need to retrieve the image from the database which we are covering in the next
page.
Example to retrieve image from Oracle
database
By the help of PreparedStatement we can retrieve and store the image in the database.
The getBlob() method of PreparedStatement is used to get Binary information, it returns
the instance of Blob. After calling the getBytes() method on the blob object, we can get
the array of binary information that can be written into the image file.
Signature of getBlob() method of PreparedStatement
1. public Blob getBlob()throws SQLException
Signature of getBytes() method of Blob interface
1. public byte[] getBytes(long pos, int length)throws SQLException
We are assuming that image is stored in the imgtable.
1. CREATE TABLE "IMGTABLE"
2. ( "NAME" VARCHAR2(4000),
3. "PHOTO" BLOB
4. )
5. /
Now let's write the code to retrieve the image from the database and write it into the
directory so that it can be displayed.
Backward Skip 10sPlay VideoForward Skip 10s
In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be
displayed by the img tag.
1. import [Link].*;
2. import [Link].*;
3. public class RetrieveImage {
4. public static void main(String[] args) {
5. try{
6. [Link]("[Link]");
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. PreparedStatement ps=[Link]("select * from imgtable");
11. ResultSet rs=[Link]();
12. if([Link]()){//now on 1st row
13.
14. Blob b=[Link](2);//2 means 2nd column data
15. byte barr[]=[Link](1,(int)[Link]());//1 means first image
16.
17. FileOutputStream fout=new FileOutputStream("d:\\[Link]");
18. [Link](barr);
19.
20. [Link]();
21. }//end of if
22. [Link]("ok");
23.
24. [Link]();
25. }catch (Exception e) {[Link](); }
26. }
27. }
Now if you see the d drive, [Link] image is created.
Example to store file in Oracle database:
The setCharacterStream() method of PreparedStatement is used to set character
information into the parameterIndex.
Syntax:
1) public void setBinaryStream(int paramIndex,InputStream stream)throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream stream,long length)throws SQLExceptio
For storing file into the database, CLOB (Character Large Object) datatype is used in the
table. For example:
1. CREATE TABLE "FILETABLE"
2. ( "ID" NUMBER,
3. "NAME" CLOB
4. )
5. /
Java Example to store file in database
1. import [Link].*;
2. import [Link].*;
3.
4. public class StoreFile {
5. public static void main(String[] args) {
6. try{
7. [Link]("[Link]");
8. Connection con=[Link](
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=[Link](
12. "insert into filetable values(?,?)");
13.
14. File f=new File("d:\\[Link]");
15. FileReader fr=new FileReader(f);
16.
17. [Link](1,101);
18. [Link](2,fr,(int)[Link]());
19. int i=[Link]();
20. [Link](i+" records affected");
21.
22. [Link]();
23.
24. }catch (Exception e) {[Link]();}
25. }
26. }
download this example
Example to retrieve file from Oracle database:
The getClob() method of PreparedStatement is used to get file information from the
database.
Syntax of getClob method
1. public Clob getClob(int columnIndex){}
Let's see the table structure of this example to retrieve the file.
1. CREATE TABLE "FILETABLE"
2. ( "ID" NUMBER,
3. "NAME" CLOB
4. )
5. /
The example to retrieve the file from the Oracle database is given below.
1. import [Link].*;
2. import [Link].*;
3.
4. public class RetrieveFile {
5. public static void main(String[] args) {
6. try{
7. [Link]("[Link]");
8. Connection con=[Link](
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. PreparedStatement ps=[Link]("select * from filetable");
12. ResultSet rs=[Link]();
13. [Link]();//now on 1st row
14.
15. Clob c=[Link](2);
16. Reader r=[Link]();
17.
18. FileWriter fw=new FileWriter("d:\\[Link]");
19.
20. int i;
21. while((i=[Link]())!=-1)
22. [Link]((char)i);
23.
24. [Link]();
25. [Link]();
26.
27. [Link]("success");
28. }catch (Exception e) {[Link](); }
29. }
30. }
Java CallableStatement Interface
CallableStatement interface is used to call the stored procedures and functions.
We can have business logic on the database by the use of stored procedures and
functions that will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you may
create a function that receives date as the input and returns age of the employee as the
output.
What is the difference between stored procedures and functions.
The differences between stored procedures and functions are given below:
Backward Skip 10sPlay VideoForward Skip 10s
Stored Procedure Function
is used to perform business logic.
is used to perform calcul
must not have the return type. must have the return typ
may return 0 or more values. may return only one valu
We can call functions from the procedure. Procedure cannot be cal
Procedure supports input and output parameters. Function supports only in
Exception handling using try/catch block can be used in stored Exception handling using
procedures. functions.
How to get the instance of CallableStatement?
The prepareCall() method of Connection interface returns the instance of
CallableStatement. Syntax is given below:
1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
The example to get the instance of CallableStatement is given below:
1. CallableStatement stmt=[Link]("{call myprocedure(?,?)}");
It calls the procedure myprocedure that receives 2 arguments.
Full example to call the stored procedure using
JDBC
To call the stored procedure, you need to create it in the database. Here, we are
assuming that stored procedure looks like this.
1. create or replace procedure "INSERTR"
2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user420 values(id,name);
7. end;
8. /
The table structure is given below:
1. create table user420(id number(10), name varchar2(200));
In this example, we are going to call the stored procedure INSERTR that receives id and
name as the parameter and inserts it into the table user420. Note that you need to
create the user420 table as well to run this application.
1. import [Link].*;
2. public class Proc {
3. public static void main(String[] args) throws Exception{
4.
5. [Link]("[Link]");
6. Connection con=[Link](
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. CallableStatement stmt=[Link]("{call insertR(?,?)}");
10. [Link](1,1011);
11. [Link](2,"Amit");
12. [Link]();
13.
14. [Link]("success");
15. }
16. }
Now check the table in the database, value is inserted in the user420 table.
Example to call the function using JDBC
In this example, we are calling the sum4 function that receives two input and returns the
sum of the given number. Here, we have used the registerOutParameter method of
CallableStatement interface, that registers the output parameter with its corresponding
type. It provides information to the CallableStatement about the type of result being
displayed.
The Types class defines many constants such as INTEGER, VARCHAR, FLOAT,
DOUBLE, BLOB, CLOB etc.
Let's create the simple function in the database first.
1. create or replace function sum4
2. (n1 in number,n2 in number)
3. return number
4. is
5. temp number(8);
6. begin
7. temp :=n1+n2;
8. return temp;
9. end;
10. /
Now, let's write the simple program to call the function.
1. import [Link].*;
2.
3. public class FuncSum {
4. public static void main(String[] args) throws Exception{
5.
6. [Link]("[Link]");
7. Connection con=[Link](
8. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9.
10. CallableStatement stmt=[Link]("{?= call sum4(?,?)}");
11. [Link](2,10);
12. [Link](3,43);
13. [Link](1,[Link]);
14. [Link]();
15.
16. [Link]([Link](1));
17.
18. }
19. }
Output: 53
Transaction Management in JDBC
Transaction represents a single unit of work.
The ACID properties describes the transaction management well. ACID stands for
Atomicity, Consistency, isolation and durability.
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another
consistent state.
Backward Skip 10sPlay VideoForward Skip 10s
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain so, even in the
event of errors, power loss etc.
Advantage of Transaction Mangaement
fast performance It makes the performance fast because database is hit at the time of
commit.
In JDBC, Connection interface provides methods to manage transaction.
Method Description
void setAutoCommit(boolean status)
It is true bydefault means e
void commit() commits the transaction.
void rollback() cancels the transaction.
Simple example of transaction management in
jdbc using Statement
Let's see the simple example of transaction management using Statement.
1. import [Link].*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. [Link]("[Link]");
5. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe"
,"system","oracle");
6. [Link](false);
7.
8. Statement stmt=[Link]();
9. [Link]("insert into user420 values(190,'abhi',40000)");
10. [Link]("insert into user420 values(191,'umesh',50000)");
11.
12. [Link]();
13. [Link]();
14. }}
If you see the table emp400, you will see that 2 records has been added.
Example of transaction management in jdbc
using PreparedStatement
Let's see the simple example of transaction management using PreparedStatement.
1. import [Link].*;
2. import [Link].*;
3. class TM{
4. public static void main(String args[]){
5. try{
6.
7. [Link]("[Link]");
8. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe"
,"system","oracle");
9. [Link](false);
10.
11. PreparedStatement ps=[Link]("insert into user420 values(?,?,?)");
12.
13. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
14. while(true){
15.
16. [Link]("enter id");
17. String s1=[Link]();
18. int id=[Link](s1);
19.
20. [Link]("enter name");
21. String name=[Link]();
22.
23. [Link]("enter salary");
24. String s3=[Link]();
25. int salary=[Link](s3);
26.
27. [Link](1,id);
28. [Link](2,name);
29. [Link](3,salary);
30. [Link]();
31.
32. [Link]("commit/rollback");
33. String answer=[Link]();
34. if([Link]("commit")){
35. [Link]();
36. }
37. if([Link]("rollback")){
38. [Link]();
39. }
40.
41.
42. [Link]("Want to add more records y/n");
43. String ans=[Link]();
44. if([Link]("n")){
45. break;
46. }
47.
48. }
49. [Link]();
50. [Link]("record successfully saved");
51.
52. [Link]();//before closing connection commit() is called
53. }catch(Exception e){[Link](e);}
54.
55. }}
Batch Processing in JDBC
Instead of executing a single query, we can execute a batch (group) of queries. It makes the
performance fast. It is because when one sends multiple statements of SQL at once to the
database, the communication overhead is reduced significantly, as one is not communicating with
the database frequently, which in turn results to fast performance.
The [Link] and [Link] interfaces provide methods for batch
processing.
Advantage of Batch Processing
Fast Performance
Methods of Statement interface
The required methods for batch processing are given below:
Method Description
The addBatch(String query
void addBatch(String query)
PreparedStatement, and Sta
The executeBatch() method
int[] executeBatch() statements. The method ret
array represents the update
If the target database facilit
boolean [Link]() throws SQLException
returns true.
void clearBatch() The method removes all th
method.
Example of batch processing in JDBC
Let's see the simple example of batch processing in JDBC. It follows following steps:
o Load the driver class
o Create Connection
o Create Statement
o Add query in the batch
o Execute Batch
o Close Connection
FileName: [Link]
1. import [Link].*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. [Link]("[Link]");
5. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");
6. [Link](false);
7.
8. Statement stmt=[Link]();
9. [Link]("insert into user420 values(190,'abhi',40000)");
10. [Link]("insert into user420 values(191,'umesh',50000)");
11.
12. [Link]();//executing the batch
13.
14. [Link]();
15. [Link]();
16. }}
If you see the table user420, two records have been added.
Example of batch processing using PreparedStatement
FileName: [Link]
1. import [Link].*;
2. import [Link].*;
3. class BP{
4. public static void main(String args[]){
5. try{
6.
7. [Link]("[Link]");
8. Connection con=[Link]("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");
9.
10. PreparedStatement ps=[Link]("insert into user420 values(?,?,?)");
11.
12. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
13. while(true){
14.
15. [Link]("enter id");
16. String s1=[Link]();
17. int id=[Link](s1);
18.
19. [Link]("enter name");
20. String name=[Link]();
21.
22. [Link]("enter salary");
23. String s3=[Link]();
24. int salary=[Link](s3);
25.
26. [Link](1,id);
27. [Link](2,name);
28. [Link](3,salary);
29.
30. [Link]();
31. [Link]("Want to add more records y/n");
32. String ans=[Link]();
33. if([Link]("n")){
34. break;
35. }
36.
37. }
38. [Link]();// for executing the batch
39.
40. [Link]("record successfully saved");
41.
42. [Link]();
43. }catch(Exception e){[Link](e);}
44.
45. }}
Output:
enter id
101
enter name
Manoj Kumar
enter salary
10000
Want to add more records y/n
y
enter id
101
enter name
Harish Singh
enter salary
15000
Want to add more records y/n
y
enter id
103
enter name
Rohit Anuragi
enter salary
30000
Want to add more records y/n
y
enter id
104
enter name
Amrit Gautam
enter salary
40000
Want to add more records y/n
n
record successfully saved
It will add the queries into the batch until user press n. Finally, it executes the batch.
Thus, all the added queries will be fired.
JDBC RowSet
An instance of RowSet is the Java bean component because it has properties and Java
bean notification mechanism. It is the wrapper of ResultSet. A JDBC RowSet facilitates a
mechanism to keep the data in tabular form. It happens to make the data more flexible
as well as easier as compared to a ResultSet. The connection between the data source
and the RowSet object is maintained throughout its life cycle. The RowSet supports
development models that are component-based such as JavaBeans, with the standard
set of properties and the mechanism of event notification.
It was in the JDBC 2.0, the support for the RowSet was introduced using the optional
packages. But the implementations were standardized for RowSet in the JDBC RowSet
Implementations Specification (JSR-114) by the Sun Microsystems that is being present
in the JDK (Java Development Kit) 5.0.
The implementation classes of the RowSet interface are as follows:
o JdbcRowSet
o CachedRowSet
o WebRowSet
o JoinRowSet
o FilteredRowSet
Let's see how to create and execute RowSet.
1. JdbcRowSet rowSet = [Link]().createJdbcRowSet();
2. [Link]("jdbc:oracle:thin:@localhost:1521:xe");
3. [Link]("system");
4. [Link]("oracle");
5.
6. [Link]("select * from emp400");
7. [Link]();
It is the new way to get the instance of JdbcRowSet since JDK 7.
Advantage of RowSet
The advantages of using RowSet are given below:
1. It is easy and flexible to use.
2. It is Scrollable and Updatable by default.
Example of JdbcRowSet
Let's see the simple example of JdbcRowSet without event handling code.
FileName: [Link]
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. [Link]("[Link]");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = [Link]().createJdbcRowSet();
16. [Link]("jdbc:oracle:thin:@localhost:1521:xe");
17. [Link]("system");
18. [Link]("oracle");
19.
20. [Link]("select * from emp400");
21. [Link]();
22.
23. while ([Link]()) {
24. // Generating cursor Moved event
25. [Link]("Id: " + [Link](1));
26. [Link]("Name: " + [Link](2));
27. [Link]("Salary: " + [Link](3));
28. }
29.
30. }
31. }
The output is given below:
Id: 55
Name: Om Bhim
Salary: 70000
Id: 190
Name: abhi
Salary: 40000
Id: 191
Name: umesh
Salary: 50000
Example of JDBC RowSet with Event Handling
To perform event handling with JdbcRowSet, you need to add the instance
of RowSetListener in the addRowSetListener method of JdbcRowSet.
The RowSetListener interface provides 3 method that must be implemented. They are
as follows:
1. public void cursorMoved(RowSetEvent event);
2. public void rowChanged(RowSetEvent event);
3. public void rowSetChanged(RowSetEvent event);
Let's write the code to retrieve the data and perform some additional tasks while the
cursor is moved, the cursor is changed, or the rowset is changed. The event handling
operation can't be performed using ResultSet, so it is preferred now.
FileName: [Link]
1. import [Link];
2. import [Link];
3. import [Link];
4. import [Link];
5. import [Link];
6. import [Link];
7. import [Link];
8. import [Link];
9.
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. [Link]("[Link]");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = [Link]().createJdbcRowSet();
16. [Link]("jdbc:oracle:thin:@localhost:1521:xe");
17. [Link]("system");
18. [Link]("oracle");
19.
20. [Link]("select * from emp400");
21. [Link]();
22.
23. //Adding Listener and moving RowSet
24. [Link](new MyListener());
25.
26. while ([Link]()) {
27. // Generating cursor Moved event
28. [Link]("Id: " + [Link](1));
29. [Link]("Name: " + [Link](2));
30. [Link]("Salary: " + [Link](3));
31. }
32.
33. }
34. }
35.
36. class MyListener implements RowSetListener {
37. public void cursorMoved(RowSetEvent event) {
38. [Link]("Cursor Moved...");
39. }
40. public void rowChanged(RowSetEvent event) {
41. [Link]("Cursor Changed...");
42. }
43. public void rowSetChanged(RowSetEvent event) {
44. [Link]("RowSet changed...");
45. }
46. }
The output is as follows:
Cursor Moved...
Id: 55
Name: Om Bhim
Salary: 70000
Cursor Moved...
Id: 190
Name: abhi
Salary: 40000
Cursor Moved...
Id: 191
Name: umesh
Salary: 50000
Cursor Moved...
Java Tutorial
Java Tutorial | Learn Java Programming
History of Java
Features of Java
C++ vs Java
Hello Java Program
Program Internal
How to set path?
JDK, JRE and JVM
JVM: Java Virtual Machine
Java Variables
Java Data Types
Unicode System
Operators in Java
Keywords
DoubleBuffer limit() methods in Java with Examples
Java short Keyword
Java long Keyword
Java Versions History
Java String valueOf()
Java Integer getInteger() Method
Package class
Java abstract Keyword
Java boolean Keyword
Java byte keyword
Java case keyword
Java char keyword
Java class keyword
Java double keyword
Java float keyword
Java int keyword
Java new Keyword
Java null reserved word
Java private keyword
Java protected keyword
Java public keyword
Java return Keyword
Control Statements
Java Control Statements
Java If-else
Java Switch
Java For Loop
Java While Loop
Java Do While Loop
Java Break
Java Continue
Java Comments
Java Programs
Java Object Class
Java OOPs Concepts
Naming Convention
Object and Class
Method in Java
Java Constructor
static keyword in Java
this keyword
Java Inheritance
Inheritance(IS-A)
Aggregation(HAS-A)
Java Polymorphism
Method Overloading
Method Overriding in Java
Covariant Return Type
super keyword
Instance Initializer block
final keyword
Runtime Polymorphism
Dynamic Binding
instanceof operator
Java Abstraction
Abstract class in Java
Interface in java
Abstract vs Interface
Java Encapsulation
Java Package
Access Modifiers
Encapsulation
Java Array
Java Array
Java OOPs Misc
Object class
Object Cloning
Math class
Wrapper Class
Java Recursion
Call by Value and Call by Reference in Java
strictfp keyword
javadoc tool
Command Line Arg
Object vs Class
Overloading vs Overriding
Java String
What is String
Immutable String
String Comparison in Java
String Concatenation in Java
Java Substring
Methods of String class
StringBuffer class
StringBuilder class
String vs StringBuffer
Difference between StringBuffer and StringBuilder
Creating Immutable class
toString method
StringTokenizer class
Java String FAQs
Java Program to reverse tOGGLE each word in String
How to optimize string creation
How to remove a particular character from a string
Java String Methods
String charAt()
String compareTo()
String concat()
String contains()
String endsWith()
String equals()
equalsIgnoreCase()
String format()
String getBytes()
String getChars()
String indexOf()
String intern()
String isEmpty()
String join()
String lastIndexOf()
Java String length() Method
String replace()
String replaceAll()
String split()
String startsWith()
String substring()
String toCharArray()
String toLowerCase()
String toUpperCase()
String trim()
Java Regex
Java Regex
Exception Handling
Java Exceptions
Java Try-catch block
Java Multiple Catch Block
Java Nested try
Java Finally Block
Java Throw Keyword
Java Exception Propagation
Java Throws Keyword
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling with Method Overriding
Java Custom Exceptions
Java Inner Class
What is inner class
Member Inner class
Anonymous Inner class
Local Inner class
static nested class
Nested Interface
Java Multithreading
What is Multithreading
Life Cycle of a Thread
How to Create Thread
Thread Scheduler
Sleeping a thread
Start a thread twice
Calling run() method
Joining a thread
Naming a thread
Thread Priority
Daemon Thread
Thread Pool
Thread Group
ShutdownHook
Performing multiple task
Garbage Collection
Runtime class
Java Synchronization
Synchronization in java
synchronized block
static synchronization
Deadlock in Java
Inter-thread Comm
Interrupting Thread
Reentrant Monitor
Java Networking
Networking Concepts
Socket Programming
URL class
URLConnection class
HttpURLConnection
InetAddress class
Java Applet
Applet Basics
Graphics in Applet
Displaying image in Applet
Animation in Applet
EventHandling in Applet
JApplet class
Painting in Applet
Digital Clock in Applet
Analog Clock in Applet
Parameter in Applet
Applet Communication
Java Reflection
Reflection API
newInstance() method
javap tool
creating javap tool
creating appletviewer
Call private method
Java Conversion
Java String to int
Java int to String
Java String to long
Java long to String
Java String to float
Java float to String
Java String to double
Java double to String
Java String to Date
Java Date to String
Java String to char
Java char to String
Java String to Object
Java Object to String
Java int to long
Java long to int
Java int to double
Java double to int
Java char to int
Java int to char
Java String to boolean
Java boolean to String
Date to Timestamp
Timestamp to Date
Binary to Decimal
Decimal to Binary
Hex to Decimal
Decimal to Hex
Octal to Decimal
Java Convert Decimal to Octal
Java JDBC
JDBC Introduction
JDBC Driver
Java Database Connectivity with 5 Steps
Connectivity with Oracle
Connectivity with MySQL
Access without DSN
DriverManager
Connection
Statement
ResultSet
PreparedStatement
ResultSetMetaData
DatabaseMetaData
Store image
Retrieve image
Store file
Retrieve file
CallableStatement
Transaction Management
Batch Processing
RowSet Interface
JDBC MCQ
RMI
Java RMI
Internationalization
Internationalization
ResourceBundle class
I18N with Date
I18N with Time
I18N with Number
I18N with Currency
Java Array Class
Java Array Class
get()
getBoolean()
getByte()
getChar()
getDouble()
getFloat()
getInt()
getLength()
getLong()
getShort()
newInstance()
set()
setBoolean()
setByte()
setChar()
setDouble()
setFloat()
setInt()
Java AtomicInteger Class
Java AtomicInteger Class
addAndGet(int delta)
compareAndSet(int expect, int update)
decrementAndGet()
doubleValue()
floatValue()
get()
getAndAdd()
getAndDecrement()
getAndSet()
incrementAndGet()
getAndIncrement()
intValue()
lazySet(int newValue)
longValue()
set(int newValue)
toString()
weakCompareAndSet(int expect,int newValue)
Java AtomicLong Methods
Java AtomicLong Methods
addAndGet()
compareAndSet()
getAndAdd()
get()
set()
decrementAndGet()
doubleValue()
floatValue()
getAndDecrement()
getAndIncrement()
getAndSet()
incrementAndGet()
intValue()
lazySet()
longValue()
toString()
weakCompareAndSet()
Java Authenticator
Java Authenticator
getPasswordAuthentication()
getRequestingHost()
getRequestingPort()
getRequestingPrompt()
getRequestingProtocol()
getRequestingScheme()
getRequestingSite()
getRequestingURL()
getRequestorType()
setDefault()
Java BigDecimal class
Java BigDecimal class
abs()
add()
divide()
doubleValue()
equals()
floatValue()
hashCode()
intValue()
intValueExact()
max()
min()
movePointLeft()
movePointRight()
multiply()
negate()
Big Integer Class
Big Integer Class
abs()
add()
and()
andNot()
bitCount()
bitLength()
clearBit()
compareTo()
divide()
divideAndRemainder()
doubleValue()
equals()
flipBit()
floatValue()
gcd()
getLowestSetBit()
hashCode()
intValue()
isProbablePrime()
longValue()
max()
min()
mod()
modInverse()
modPow()
negate()
nextProbablePrime()
not()
or()
pow()
probablePrime()
setBit()
shiftLeft()
shiftRight()
signum()
subtract()
testbit()
toByteArray()
toString()
valueOf()
xor()
Java Boolean class
Java Boolean class
booleanValue()
compare()
compareTo()
Java Boolean equals () Method
getBoolean()
hashCode()
logicalAnd()
logicalOr()
logicalXor()
parseBoolean()
toString()
valueOf()
Java Byte Class
Java Byte
byteValue()
compare()
compareTo()
compareUnsigned()
decode()
doubleValue()
equals()
floatValue()
hashCode()
intValue()
longValue()
parseByte()
shortValue()
toString()
toUnsignedInt()
toUnsignedLong()
valueOf()
Java Class
Java Class
asSubclass()
Cast()
desiredAssertionStatus()
forName()
getAnnotatedInterfaces()
getAnnotatedSuperclass()
getAnnotation()
getAnnotationsByType()
getAnnotations()
getCanonicalName()
getClasses()
getClassLoader()
getComponentType
getConstructor()
getConstructors()
getDeclaredAnnotation()
getDeclaredAnnotationsByType()
getDeclaredAnnotations()
getDeclaredConstructor()
getDeclaredConstructors()
getDeclaredField()
getDeclaredFields()
getDeclaredMethod()
getDeclaredMethods()
getDeclaringClass()
getField()
getFields()
getGenericInterfaces()
getGenericSuperClass()
getInterfaces()
getMethod()
getMethods()
getModifiers()
getName()
getPackage()
getPackageName()
getProtectionDomain()
getResource()
getSigners()
getSimpleName()
getSuperClass()
isAnnotation()
isAnnotationPresent()
isAnonymousClass()
isArray()
isInstance()
isInterface()
isPrimitive()
isSynthetic()
Java Collections class
Java Collections class
addAll()
asLifoQueue()
binarySearch()
checkedCollection()
checkedList()
checkedMap()
checkedNavigableMap()
checkedNavigableSet()
checkedQueue()
checkedSet()
checkedSortedMap()
checkedSortedSet()
copy()
disjoint()
emptyEnumeration()
emptyIterator()
emptyList()
emptyListIterator()
emptyMap()
emptyNavigableMap()
emptyNavigableSet()
emptySet()
emptySortedMap()
emptySortedSet()
enumeration()
fill()
frequency()
indexOfSubList()
lastIndexOfSubList()
list()
max()
min()
nCopies()
newSetFromMap()
replaceAll()
reverse()
reverseOrder()
rotate()
shuffle()
singleton()
singletonList()
singletonMap()
Java Collections sort() Method
swap()
synchronizedCollection()
synchronizedList()
synchronizedMap()
synchronizedNavigableMap()
synchronizedNavigableSet()
synchronizedSet()
synchronizedSortedMap()
synchronizedSortedSet()
unmodifiableCollection()
unmodifiableList()
unmodifiableMap()
unmodifiableNavigableMap()
unmodifiableNavigableSet()
unmodifiableSet()
unmodifiableSortedMap()
unmodifiableSortedSet()
Java Compiler Class
Java Compiler
command()
compileClass()
compileClasses()
disable()
enable()
CopyOnWriteArrayList
Java CopyOnWriteArrayList
indexOf()
lastIndexOf()
clone()
toArray()
Java Math Methods
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
Math.log10()
Math.log1p()
[Link]()
Math.expm1()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]
[Link]
LinkedBlockingDeque
Java LinkedBlockingDeque
addFirst()
add()
addAll()
addLast()
clear()
contains()
descendingIterator()
drainTo()
element()
getFirst()
getLast()
iterator()
offerFirst()
offerLast()
offer()
peek()
peekFirst()
peekLast()
pollFirst()
pollLast()
poll()
pop()
Java Long class
Java Long class
LinkedTransferQueue
Java LinkedTransferQueue
add()
contains()
isEmpty()
iterator()
offer()
remove()
size()
spliterator()
drainTo()
peek()
poll()
put()
take()
Java List
Difference between Array and ArrayList
When to use ArrayList and LinkedList in Java
Difference between ArrayList and Vector
How to Compare Two ArrayList in Java
How to reverse ArrayList in Java
When to use ArrayList and LinkedList in Java
How to make ArrayList Read Only
Difference between length of array and size() of ArrayList in Java
How to Synchronize ArrayList in Java
How to convert ArrayList to Array and Array to ArrayList in java
Array vs ArrayList in Java
How to Sort Java ArrayList in Descending Order
How to remove duplicates from ArrayList in Java
Java MulticastSocket
Java MulticastSocket
getInterface()
getLoopbackMode()
getNetworkInterface()
getTimeToLive()
getTTL()
joinGroup()
leaveGroup()
setInterface()
setLoopbackMode()
setNetworkInterface()
setTimeToLive()
setTTL()
Java Number Class
Java Number Class
byteValue()
doubleValue()
floatValue()
intValue()
longValue()
shortValue()
Java Phaser Class
Java Phaser
getPhase()
register()
arriveAndAwaitAdvance()
arriveAndDeregister()
arrive()
getParent()
awaitAdvanceInterruptibly()
awaitAdvance()
bulkRegister()
forceTermination()
getArrivedParties()
getRegisteredParties()
getRoot()
getUnarrivedParties()
isTerminated()
ArrayList Methods
add
addAll
addAll
clear
Iterator()
listIterator()
remove
removeAll
removeRange
retainAll
Java Thread Methods
start()
run()
sleep()
currentThread()
join()
getPriority()
setPriority()
getName()
setName()
getId()
isAlive()
yield()
suspend()
resume()
stop()
destroy()
isDaemon()
setDaemon()
interrupt()
isinterrupted()
interrupted()
activeCount()
checkAccess()
holdLock()
dumpStack()
getStackTrace()
enumerate()
getState()
getThreadGroup()
toString()
notify()
notifyAll()
setContextClassLoader()
getContextClassLoader()
getDefaultUncaughtExceptionHandler()
setDefaultUncaughtExceptionHandler()
Java Projects
Free Java Projects
Payment Bill(JSP)
Transport (JSP)
Connect Globe (JSP)
Online Banking (JSP)
Online Quiz (JSP)
Classified (JSP)
Mailcasting (JSP)
Online Library (JSP)
Pharmacy (JSP)
Mailer (Servlet)
Baby Care (Servlet)
Chat Server (Core)
Library (Core)
Exam System (Core)
Java Apps (Core)
Fee Report (Core)
Fee (Servlet)
eLibrary (Servlet)
Fire Detection
Attendance System
Java Programs
Fibonacci Series in Java
Prime Number Program in Java
Palindrome Program in Java
Factorial Program in Java
Armstrong Number in Java
How to Generate Random Number in Java
How to Print Pattern in Java
How to Compare Two Objects in Java
How to Create Object in Java
How to Print ASCII Value in Java
How to Reverse a Number in Java
Java Program to convert Number to Word
Automorphic Number Program in Java
Peterson Number in Java
Sunny Number in Java
Tech Number in Java
Fascinating Number in Java
Keith Number in Java
Neon Number in Java
Spy Number in Java
ATM program Java
Autobiographical Number in Java
Emirp Number in Java
Sphenic Number in Java
Buzz Number Java
Duck Number Java
Evil Number Java
ISBN Number Java
Krishnamurthy Number Java
Bouncy Number in Java
Mystery Number in Java
Smith Number in Java
Strontio Number in Java
Xylem and Phloem Number in Java
nth Prime Number Java
Java Program to Display Alternate Prime Numbers
Java Program to Find Square Root of a Number Without sqrt Method
Java Program to Swap Two Numbers Using Bitwise Operator
Java Program to Find GCD of Two Numbers
Java Program to Find Largest of Three Numbers
Java Program to Find Smallest of Three Numbers Using Ternary Operator
Java Program to Check if a Number is Positive or Negative
Java Program to Check if a Given Number is Perfect Square
Java Program to Display Even Numbers From 1 to 100
Java Program to Display Odd Numbers From 1 to 100
Java Program to Find Sum of Natural Numbers
Java Program to copy all elements of one array into another array
Java Program to find the frequency of each element in the array
Java Program to left rotate the elements of an array
Java Program to print the duplicate elements of an array
Java Program to print the elements of an array
Java Program to print the elements of an array in reverse order
Java Program to print the elements of an array present on even position
Java Program to print the elements of an array present on odd position
Java Program to print the largest element in an array
Java Program to print the smallest element in an array
Java Program to print the number of elements present in an array
Java Program to print the sum of all the items of the array
Java Program to right rotate the elements of an array
Java Program to sort the elements of an array in ascending order
Java Program to sort the elements of an array in descending order
Java Program to Find 3rd Largest Number in an array
Java Program to Find 2nd Largest Number in an array
Java Program to Find Largest Number in an array
Java to Program Find 2nd Smallest Number in an array
Java Program to Find Smallest Number in an array
Java Program to Remove Duplicate Element in an array
Java Program to Print Odd and Even Numbers from an array
How to Sort an Array in Java
Java Matrix Programs
Java Program to Add Two Matrices
Java Program to Multiply Two Matrices
Java Program to subtract the two matrices
Java Program to determine whether two matrices are equal
Java Program to display the lower triangular matrix
Java Program to display the upper triangular matrix
Java Program to find the frequency of odd & even numbers in the given matrix
Java Program to find the product of two matrices
Java Program to find the sum of each row and each column of a matrix
Java Program to find the transpose of a given matrix
Java Program to determine whether a given matrix is an identity matrix
Java Program to determine whether a given matrix is a sparse matrix
Java Program to Transpose matrix
Java Program to count the total number of characters in a string
Java Program to count the total number of characters in a string 2
Java Program to count the total number of punctuation characters exists in a
String
Java Program to count the total number of vowels and consonants in a string
Java Program to determine whether two strings are the anagram
Java Program to divide a string in 'N' equal parts.
Java Program to find all subsets of a string
Java Program to find the longest repeating sequence in a string
Java Program to find all the permutations of a string
Java Program to remove all the white spaces from a string
Java Program to replace lower-case characters with upper-case and vice-versa
Java Program to replace the spaces of a string with a specific character
Java Program to determine whether a given string is palindrome
Java Program to determine whether one string is a rotation of another
Java Program to find maximum and minimum occurring character in a string
Java Program to find Reverse of the string
Java program to find the duplicate characters in a string
Java program to find the duplicate words in a string
Java Program to find the frequency of characters
Java Program to find the largest and smallest word in a string
Java Program to find the most repeated word in a text file
Java Program to find the number of the words in the given text file
Java Program to separate the Individual Characters from a String
Java Program to swap two string variables without using third or temp variable.
Java Program to print smallest and biggest possible palindrome word in a given
string
Reverse String in Java Word by Word
Reserve String without reverse() function
Linear Search in Java
Binary Search in Java
Bubble Sort in Java
Selection Sort in Java
Insertion Sort in Java
How to convert String to int in Java
How to convert int to String in Java
How to convert String to long in Java
How to convert long to String in Java
How to convert String to float in Java
How to convert float to String in Java
How to convert String to double in Java
How to convert double to String in Java
How to convert String to Date in Java
How to convert Date to String in Java
How to convert String to char in Java
How to convert char to String in Java
How to convert String to Object in Java
How to convert Object to String in Java
How to convert int to long in Java
How to convert long to int in Java
How to convert int to double in Java
How to convert double to int in Java
How to convert char to int in Java
How to convert int to char in Java
How to convert String to boolean in Java
How to convert boolean to String in Java
How to convert Date to Timestamp in Java
How to convert Timestamp to Date in Java
How to convert Binary to Decimal in Java
How to convert Decimal to Binary in Java
How to convert Hex to Decimal in Java
How to convert Decimal to Hex in Java
How to convert Octal to Decimal in Java
How to convert Decimal to Octal in Java
Java program to print the following spiral pattern on the console
Java program to print the following pattern
Java program to print the following pattern 2
Java program to print the following pattern 3
Java program to print the following pattern 4
Java program to print the following pattern 5
Java program to print the following pattern on the console
Java program to print the following pattern on the console 2
Java program to print the following pattern on the console 3
Java program to print the following pattern on the console 4
Java program to print the following pattern on the console 5
Java program to print the following pattern on the console 6
Java program to print the following pattern on the console 7
Java program to print the following pattern on the console 8
Java program to print the following pattern on the console 9
Java program to print the following pattern on the console 10
Java program to print the following pattern on the console 11
Java program to print the following pattern on the console 12
Singly linked list Examples in Java
Java Program to create and display a singly linked list
Java program to create a singly linked list of n nodes and count the number of
nodes
Java program to create a singly linked list of n nodes and display it in reverse
order
Java program to delete a node from the beginning of the singly linked list
Java program to delete a node from the middle of the singly linked list
Java program to delete a node from the end of the singly linked list
Java program to determine whether a singly linked list is the palindrome
Java program to find the maximum and minimum value node from a linked list
Java Program to insert a new node at the middle of the singly linked list
Java program to insert a new node at the beginning of the singly linked list
Java program to insert a new node at the end of the singly linked list
Java program to remove duplicate elements from a singly linked list
Java Program to search an element in a singly linked list
Java program to create and display a Circular Linked List
Java program to create a Circular Linked List of N nodes and count the number
of nodes
Java program to create a Circular Linked List of n nodes and display it in reverse
order
Java program to delete a node from the beginning of the Circular Linked List
Java program to delete a node from the end of the Circular Linked List
Java program to delete a node from the middle of the Circular Linked List
Java program to find the maximum and minimum value node from a circular
linked list
Java program to insert a new node at the beginning of the Circular Linked List
Java program to insert a new node at the end of the Circular Linked List
Java program to insert a new node at the middle of the Circular Linked List
Java program to remove duplicate elements from a Circular Linked List
Java program to search an element in a Circular Linked List
Java program to sort the elements of the Circular Linked List
Java program to convert a given binary tree to doubly linked list
Java program to create a doubly linked list from a ternary tree
Java program to create a doubly linked list of n nodes and count the number of
nodes
Java program to create a doubly linked list of n nodes and display it in reverse
order
Java program to create and display a doubly linked list
Java program to delete a new node from the beginning of the doubly linked list
Java program to delete a new node from the end of the doubly linked list
Java program to delete a new node from the middle of the doubly linked list
Java program to find the maximum and minimum value node from a doubly linked
list
Java program to insert a new node at the beginning of the Doubly Linked list
Java program to insert a new node at the end of the Doubly Linked List
Java program to insert a new node at the middle of the Doubly Linked List
Java program to remove duplicate elements from a Doubly Linked List
Java program to rotate doubly linked list by N nodes
Java program to search an element in a doubly linked list
Java program to sort the elements of the doubly linked list
Java Program to calculate the Difference between the Sum of the Odd Level and
the Even Level Nodes of a Binary Tree
Java program to construct a Binary Search Tree and perform deletion and In-
order traversal
Java program to convert Binary Tree to Binary Search Tree
Java program to determine whether all leaves are at same level
Java program to determine whether two trees are identical
Java program to find maximum width of a binary tree
Java program to find the largest element in a Binary Tree
Java program to find the maximum depth or height of a tree
Java program to find the nodes which are at the maximum distance in a Binary
Tree
Java program to find the smallest element in a tree
Java program to find the sum of all the nodes of a binary tree
Java program to find the total number of possible Binary Search Trees with N
keys
Java program to implement Binary Tree using the Linked List
Java program to search a node in a Binary Tree
Candy Distribution Problem in Java
Find Rectangle in a Matrix with Corner as 1 in Java
Minimum Number of Taps to Open to Water a Garden in Java
Seven Segment Display Problem in Java
Split Array Largest Sum in Java
Find Original Array from a Double Array in Java
Minimum Lights to Activate Problem in Java
Rotate List in Java
Count of Range Sum Problem in Java
Create A Tree of Coprime in Java
Convert Integer to Roman Numerals in Java
Check if n and its Double Exist or not in Java
Array of Doubled Pair Problem in Java
Tag Content Extractor Problem in Java
Convert Roman to Integer in Java
Minimum Number of Flips to Convert Binary Matrix into Zero Matrix in Java
XOR of Array Elements Except Itself in Java
Check If the Given Array is Mirror Inverse in Java
How to Create a Mirror Image of A 2D Array in Java
Add Numbers Represented by Linked Lists in Java
Majority Element In an Array in Java
Block Swap Algorithm or Array Rotation in Java
Minimum Difference Among Group Size Two in Java
Missing Number in An Arithmetic Progression in Java
Peak Index of Mountain Array Problem in Java
Minimum Number of Meeting Room Required Problem in Java
Move Zeros to End in Java
Count Inversions in an array in Java
Count Smaller Elements on The Right Side in Java
Interleaving String Problem in Java
Bulb Chain Problem in Java
Java Misc
Java Main Method
[Link]()
Java Memory Management
Java ClassLoader
Java Heap
Java Decompiler
Java UUID
Java JRE
Java SE
Java EE
Java ME
Java vs. JavaScript
Java vs. Kotlin
Java vs. Python
Java Absolute Value
How to Create File
Delete a File in Java
Open a File in Java
Sort a List in Java
Convert byte Array to String
Java Basics
How to Compile & Run Java Program
How to Run Java Program in Eclipse
How to Verify Java Version
Ways to Create an Object in Java
How to Run a Java program in Windows 10
Runnable Interface in Java
Reserve String without reverse() function
How to Reverse String in Java
Java Keystore
Get input from user in Java
Read file line by line in Java
Take String input in Java
How to Read Excel File in Java
Read XML File in Java
CompletableFuture in Java
Java ExecutorService
How to iterate Map in Java
How to Return an Array in Java
How to Sort HashMap by Value
How to Sort HashMap in Java
Load Factor in HashMap
Array vs ArrayList
HashMap vs TreeMap
HashSet vs HashMap class
Compare Two ArrayList in Java
Merge Two Arrays in Java
Print Array in Java
Read CSV File in Java
Remove Special Characters from String
ArrayIndexOutOfBoundsException
ConcurrentModificationException
NoSuchElementException
NumberFormatException
How to Sort ArrayList in Java
Java Stack
How to Create Object in Java
How to Print ASCII Value in Java
How to Generate Random Number in Java
How to Sort an Array in Java
How to Download Java
How to Compare Two Objects in Java
How to Call a Method in Java
How to Print Pattern in Java
How to Create Singleton Class in Java
How to Find Array Length in Java
How to Read Character in Java
How to Reverse a Number in Java
Can We Overload main() Method in Java
How to Convert Char Array to String in Java
How to Run Java Program in CMD Using Notepad
How to Sort String Array in Java
How to Compare Dates in Java
How to Take Multiple String Input in Java Using Scanner
How to Remove Last Character from String in Java
How TreeMap Works Internally in Java
Java Program to Find Sum of Natural Numbers
Java Program to Display Alternate Prime Numbers
Java Program to Find Square Root of a Number Without sqrt Method
Java Program to Swap Two Numbers Using Bitwise Operator
Java Program to Break Integer into Digits
Java Program to Find GCD of Two Numbers
Java Program to Find Largest of Three Numbers
Java Program to Calculate Area and Circumference of Circle
Java Program to Check if a Number is Positive or Negative
Java Program to Find Smallest of Three Numbers Using Ternary Operator
What is Diamond Problem in Java
Java Program to Check if a Given Number is Perfect Square
Java Program to Display Even Numbers From 1 to 100
Java Program to Display Odd Numbers From 1 to 100
Java Program to Read Number from Standard Input
How to Download Minecraft Java Edition
Can We Override Static Method in Java
How to Avoid Deadlock in Java
How to Achieve Abstraction in Java
How Garbage Collection Works in Java
How to Take Array Input in Java
How to Create Array of Objects in Java
How to Create Package in Java
How to Print in Java
What is Framework in Java
Why Java is Secure
How to Iterate List in Java
How to Use Eclipse for Java
Which Package is Imported by Default in Java
Could Not Find or Load Main Class in Java
How to Compare Two Arrays in Java
How to Convert String to JSON Object in Java
Which is Better Java or Python
How to Update Java
C vs Java
How to Get Value from JSON Object in Java Example
How to Split a String in Java with Delimiter
Structure of Java Program
Why We Use Constructor in Java
Java Create Excel File
Java Interpreter
javac is not Recognized
Dynamic Array in Java
Shunting yard algorithm
Java Destructor
Custom ArrayList in Java
ArrayList vs HashMap
Java Constant
Java Tokens
Java Xmx
How to Enable Java in Chrome
Java Semaphore
Array to List in Java
JIT in Java
How to Clear Screen in Java
Java IDEs
Java Logger
Reverse a String Using Recursion in Java
Java Path Vs File
Float Vs Double Java
Stack vs Heap Java
Abstraction vs Encapsulation
Top 10 Java Books
Public vs Private
What is Java Used For
Bitwise Operator in Java
SOLID Principles Java
Type Casting in Java
Conditional Operator in Java
Ternary Operator Java
Java Architecture
REPL in Java
Types of Exception in Java
Why String is Immutable or Final in Java
Java vs Kotlin
Set in Java
Why non-static variable cannot be referenced from a static context in Java
Java Developer Roles and Responsibilities
Types of Classes in Java
Marker Interface in Java
Static Function in Java
Unary Operators in Java
What is Advance Java
ArrayList Implementation
Convert ArrayList to String Array
Hashmap vs ConcurrentHashMap
List vs ArrayList
Map vs HashMap
HashSet vs LinkedHashSet
How TreeSet Works Internally
LinkedHashMap vs HashMap
Java Program to Solve Quadratic Equation
Scope Resolution Operator in Java
Composition in Java
File Operations in Java
NoClassDefFoundError in Java
Thread Concept in Java
Upcasting and Downcasting in Java
Dynamic Polymorphism in Java
Java Robot
String Pool in Java
What is constructor chaining in Java
Add elements to Array in Java
Advantages and disadvantages of Java
Advantages of JavaBeans
AWS SDK for Java with Apache Maven
AWT and Swing in Java
AWT Program in Java
Boolean values in Java
ByteStream Classes in Java
CharacterStream Classes in Java
Class and Interface in Java
ClassCast Exception in Java
Cloneable in Java
Constructor overloading in Java
Control Flow in Java
Convert Java Object to Json using GSON
Convert XML to JSON in Java
How to avoid null pointer exception in Java
Java constructor returns a value, but what
Singleton Class in Java
Doubly Linked List Program in Java
Java 12
Association in Java
Big data Java vs Python
Branching Statements in Java
Collections Sort in Java 8
List vs Set in Java
How many days required to learn Java
Implicitly Typecasting in Java
Legacy Class in Java
Character Array in Java
Equals() and Hashcode() in Java
Externalization in Java
Identifiers in Java
InvocationTargetException
Java Pass by Value
Mutable and Immutable in Java
POJO
Power Function in Java
Primitive Data Types in Java
String Array in Java
Virtual Function in Java
C vs C++ vs Java
Java String Max Size
nth Prime Number Java
Convert Java object to JSON
How to Calculate Date Difference in Java
How to Improve Coding Skills in Java
Java Email Validation
Java Testing Tools
Permutation and Combination in Java
JavaCC
Unique Number in Java Program
JDBC MCQ
OOPs MCQ
Java Code for DES
Pig Latin Program in Java
Array Rotation in Java
Equilibrium Index of an Array in Java
Different Ways to Print Exception Message in Java
Java Copy Constructor Example
Why We Use Static Class in Java
What is Core Java
Set vs Map in Java
How to Create a New Folder in Java
Remove an Element from ArrayList in Java
How to Create Test Cases for Exceptions in Java
How to Convert JSON Array to ArrayList in Java
How to Create a Class File in Java
Java Spring Pros & Cons
Java Stack Trace
Array Slicing in Java
Flutter vs Java
Permutation of Numbers in Java
Magic Number in Java
Reference Data Types in Java
Counter variable in Java
How to take Character Input in Java using BufferedReader Class
Java employee details program
Java is case sensitive explain
Ramanujan Number or Taxicab Number in Java
Advanced Java Books in 2021
Fail Fast and Fail Safe Iterator in Java
How to build a Web Application Using Java
Is Java Interpreted or Compiled
Java Big Data Frameworks
Java Get Data From URL
No Main Manifest Attribute
Java missing return statement
Java program to remove duplicate characters from a string
JUnit test case example in Java
List of logical programs in Java
PermGen space Java
Unsigned Right Shift Operator in Java
Infix to Postfix Java
Memory Leak in Java
How To Write Test Cases In Java
Java 32-Bit Download For Windows 10
FizzBuzz Program in Java
Java Graph
A Java Runtime Environment JRE Or JDK Must Be Available
Java Does Not Open
No Java Virtual Machine was Found
Java Program Number to Word
Types of Garbage Collector in Java
No Suitable Driver Found For JDBC
AVL Tree program in Java
Fail-fast and Fail-safe in Java
Find unique elements in array Java
Highest precedence in Java
Java Closure
Java String Encoding
Prim's algorithm Java
Quartz scheduler java
Red Black Tree Java
GC Overhead Limit Exceeded
Generating QR Code in Java
Delegation Event Model in Java
Java Pair
Java Profilers
Java XOR
Java Flight Recorder
Bucket Sort in Java
Automorphic Number Program in Java
Java Atomic
Wait vs Sleep in Java
Executor Framework Java
Gregorian calendar Java
int vs Integer Java
What is truncation in Java
Peterson Number in Java
Sunny Number in Java
Tech Number in Java
Java HTTP Proxy Server
Java Static Constructor
How to prepare for Java Interview
Java callback function
Java 8 vs Java 11
Login Form Java
Vaadin Framework Java
EJB vs. Spring
Fascinating Number in Java
Keith Number in Java
Neon Number in Java
Spy Number in Java
Types of Applets in Java
Visitor Design Pattern Java
Advantages of Python over Java
ATM program Java
Design Principles in Java
JSON Validator Java
Pseudocode Java
Autobiographical Number in Java
Emirp Number in Java
Sphenic Number in Java
Windows Programming Using Java
Buzz Number Java
Duck Number Java
Evil Number Java
ISBN Number Java
Krishnamurthy Number Java
Vert.x Java
Bouncy Number in Java
Mystery Number in Java
Smith Number in Java
Strontio Number in Java
Xylem and Phloem Number in Java
Complex Java Programs
ORE Number Java
PalPrime Number Java
Twin Prime Numbers
Twisted Prime Number Java
Ugly number Java
Achilles Number in Java
Amicable Pair Number in Java
Playfair Cipher Program in Java
[Link]: java heap space
Banker's Algorithm Java
Kruskal Algorithm Java
Longest Common Subsequence
Travelling Salesman Problem
& vs && in Java
Jumping Number in Java
Lead Number in Java
Lucky Number in Java
Middle Digit Number in Java
Special Number in Java
Passing Array to Function In Java
Java Error
Java Apps
Lexicographical Order Java
Adam Number in Java
Bell Number in Java
Reduce Java
LRU Cache Implementation
Goldbach Number in Java
How to Find Number of Objects Created in Java
Multiply Two Numbers Without Using Arithmetic Operator in Java
Sum of Digits of a Number in Java
Sum of Numbers in Java
Power of a Number in Java
Sum of Prime Numbers in Java
Cullen Number in Java
Mobile Number Validation in Java
Fermat Number in Java
Instantiation in Java
Exception Vs Error in Java
flatMap() Method in Java 8
How to Print Table in Java
Java Create PDF
Mersenne Number in Java
Pandigital Number in Java
Pell Number in Java
Java Get Post
Fork Join in Java
Java Callable Example
Blockchain Java
Design of JDBC
Java Anon Proxy
Knapsack Problem Java
Session Tracking in Java
What is Object-Oriented Programming
Literals in Java
Square Free Number in Java
What is an anagram in Java
What is programming
Iterate JSON Array Java
Java Date Add Days
Java Plot
Javac Command Not Found
Factorial Program in Java Using while Loop
Frugal Number in Java
Java Digital Signature
Catalan Number in Java
Partition Number in Java
Powerful Number in Java
Practical Number in Java
Chromatic Number in Java
Sublime Number in Java
Advanced Java Viva Questions
Getter and Setter Method in Java Example
How to convert String to String array in Java
How to Encrypt Password in Java
Instance Variable in Java
Java File Extension
Java Pi
Java Pop
Types of Inheritance in Java
Untouchable Number in Java
AES 256 Encryption in Java
Applications of Array in Java
Example of Static Import in Java
Hill Cipher Program in Java
Lazy Loading in Java
Rectangular Number in Java
How to Print Table in Java Using Formatter
Java IdentityHashMap Class
Java BF
Java Logo
Undulating Number in Java
Java Obfuscator
Java Switch String
Applet Life Cycle in Java
Banking Application in Java
Duodecimal in Java
Economical Number in Java
Figurate Number in Java
How to resolve IllegalStateException in Java
Java Coding Software
Java Create Jar Files
Java Framework List
Java Initialize array
java lang exception no runnable methods
Java Queue
Nonagonal Number in Java
SexagesimalFormatter in Java
Sierpinski Number in Java
Vigesimal in Java
Java Color Codes
JDoodle Java
Online Java Compiler
Pyramidal Number in Java
Relatively Prime in Java
Java Modulo
Repdigit Numbers in Java
Abstract Method in Java
Convert Text-to-Speech in Java
Java Editors
MVC Architecture in Java
Narcissistic Number in Java
Hashing Algorithm in Java
Java Escape Characters
Java Operator Precedence
Private Constructor in Java
Scope of Variables in Java
Groovy vs Java
Java File Upload to a Folder
Java Full Stack
Java Developer
Thread States in Java
Java EE vs [Link]
Java Image
Loose Coupling in Java
Java Top 10 Libraries
Method Hiding in Java
Java Tuple
Dijkstra Algorithm Java
Extravagant Number in Java
Java Unicode
New Line in Java
Return Statement in Java
Order of Execution of Constructors in Java Inheritance
Cardinal Number in Java
Hyperfactorial in Java
Identifier Expected Error in Java
Java Generate UUID
Labeled Loop in Java
Lombok Java
Ordinal Number in Java
Tetrahedral Number in Java
Cosmic Superclass in Java
Shallow Copy Java
BiFunction Java 8
Equidigital Number in Java
Fall Through in Java
Java Reserved Keywords
Java Vs Go
Parking Lot Design Java
Boyer Moore Java
Java Security Framework
Tetranacci Number in Java
BFS Algorithm in Java
CountDownLatch in Java
Counting sort in Java
CRC Program in Java
FileNotFoundException in Java
InputMismatchException in Java
Java ASCII Table
Spark Java
Lock in Java
Segment Tree in Java
DTO Java
Why main() method is always static in Java
Bellman-Ford Algorithm Java
BigDecimal toString() in Java
.NET vs Java
Java ZipFile
Lazy Propagation in Segment Tree in Java
Magnanimous Number in Java
Binary Tree Java
How to Create Zip File in Java
Java Dot Operator
Associativity of Operators in Java
Fenwick Tree in Java
How annotation works in Java
How to Find Length of Integer in Java
Java 8 filters
List All Files in a Directory in Java
TDD Java
How to Get Day Name from Date in Java
Zigzag Array in Java
Class Definition in Java
Find Saddle Point of a Matrix in Java
Non-primitive data types in Java
Pancake Number in Java
Pancake Sorting in Java
Print Matrix Diagonally in Java
Sort Dates in Java
Carmichael Numbers in Java
Contextual Keywords in Java
How to Open Java Control Panel
How to Reverse Linked List in Java
Interchange Diagonal Elements Java Program
Java Set to List
Level Order Traversal of a Binary Tree in Java
Bully algorithm in Java
Convert JSON File to String in Java
Convert Milliseconds to Date in Java
Copy Content/ Data From One File to Another in Java
Constructor vs Method in Java
Access Specifiers vs Modifiers
Java vs PHP
replace() vs replaceAll() in Java
this vs super in Java
Heap implementation in Java
How to Check null in Java
Java Arrays Fill
Java Font
Rotate Matrix by 90 Degrees in Java
Exception Class in Java
Transient variable in Java
Web crawler Java
Zigzag Traversal of a Binary Tree in Java
Java Get File Size
Internal Working of ArrayList in Java
Java Program to Print Matrix in Z Form
Vertical Order Traversal of a Binary Tree in Java
Group By in Java 8
Hashing Techniques in Java
Implement Queue Using Array in Java
Java 13 Features
Package Program in Java
Canonical Name Java
Method Chaining in Java
Orphaned Case Java
Bottom View of a Binary Tree in Java
Coercion in Java
Dictionary Class in Java
Left View of a Binary Tree in Java
Pangram Program in Java
Top View of a Binary Tree in Java
Tribonacci Series in Java
Hollow Diamond Pattern in Java
Normal and Trace of a Matrix in Java
Right View of a Binary Tree in Java
Dining Philosophers Problem and Solution in Java
Shallow Copy vs Deep Copy in Java
Java Password Generator
Java Program for Shopping Bill
Lock Interface in Java
Convert JSON to Map in Java
Convert JSON to XML in Java
Middle Node of a Linked List in Java
Pernicious Number in Java
Cohesion in Java
How to get UTC time in Java
Jacobsthal Number in Java
Java BLOB
Java Calculate Age
JFC Java
Tribonacci Number Java
Bernoulli number in Java
Cake Number in Java
Compare time in Java
Compare Two Sets in Java
Crown Pattern in Java
Convert List to Array in Java
Aggregation vs Composition
Morris Traversal for Inorder in Java
Morris Traversal for Preorder in Java
Package Naming Conversion in Java
India Map Pattern in Java
Ladder Pattern in Java
ORM Tools in Java
Odious Number in Java
Rat in a Maze Problem in Java
Sudoku in Java
Christmas Tree Pattern in Java
Double Hashing in Java
Magic Square in Java
Possible Paths from Top Left to Bottom Right of a Matrix in Java
Palindrome Partitioning Problem in Java
Rehashing in Java
Round Robin Scheduling Program in Java
Types of Statements in Java
Compound Assignment Operator in Java
Prime Points in Java
Butterfly Pattern in Java
Fish Pattern in Java
Flag Pattern in Java
Kite pattern in Java
Swastika Pattern in Java
Tug of War in Java
Clone HashMap in Java
Fibodiv Number in Java
Heart Pattern in Java
How to check data type in Java
Java Array Clone
Use of final Keyword in Java
Factorial of a Large Number in Java
Race Condition in Java
Static Array in Java
Water Jug Problem in Java
Electricity Bill Program in Java
Facts about null in Java
Maximizing Profit in Stock Buy Sell in Java
Permutation Coefficient in Java
Convert List to String in Java
List of Constants in Java
MOOD Factors to Assess a Java Program
Computing Digit Sum of All Numbers From 1 to n in Java
Read PDF File in Java
Finding Odd Occurrence of a Number in Java
Java Indentation
Zig Zag Star and Number Pattern in Java
Check Whether a Number is a Power of 4 or not in Java
Kth Smallest in an Unsorted Array in Java
BlockingQueue in Java
Next Greater Element in Java
Star Numbers in Java
3N+1 Problem in Java
Java Program to Find Local Minima in An Array
Processing Speech in Java
Java Output Formatting
House Numbers in Java
Java Program to Generate Binary Numbers
Longest Odd-Even Subsequence in Java
Java Subtract Days from Current Date
Java Future Example
Minimum Cost Path Problem in Java
Diffie-Hellman Algorithm in Java
Ganesha's Pattern in Java
Hamming Code in Java
Map of Map in Java
Print Pencil Shape Pattern in Java
Zebra Puzzle in Java
Display Unique Rows in a Binary Matrix in Java
Rotate A Matrix By 180 Degree in Java
Dangling Else Problem in Java
Java Application vs Java Applet
Dutch National Flag Problem in Java
Java Calculate Average of List
compareToIgnoreCase Java
Trimorphic Numbers in Java
Arithmetic Exception in Java
Java instanceof operator
Java Localization
Minimum XOR Value Pair in Java
Iccanobif Numbers in Java
Java Program to Count the Occurrences of Each Character
Java Technologies List
Java Program to Find the Minimum Number of Platforms Required for a Railway
Station
Shift Operators in Java
Final Object in Java
Java OCR
Object Definition in Java
Shadowing in Java
Zipping and Unzipping Files in Java
Display the Odd Levels Nodes of a Binary Tree in Java
Java Variable Declaration
Nude Numbers in Java
Java Programming Challenges
Java URL Encoder
anyMatch() in Java 8
Sealed Class in Java
Camel case in Java
Career Options for Java Developers to Aim in 2022
Java Progress Bar
Maximum Rectangular Area in a Histogram in Java
Polygonal Number in Java
Two Sorted LinkedList Intersection in Java
Set Matrix Zeros in Java
Find Number of Island in Java
Balanced Prime Number in Java
Minecraft Bedrock vs Java Minecraft
[Link] vs arr[0].length vs arr[1].length in Java
Future in Java 8
How to Set Timer in Java
Construct the Largest Number from the Given Array in Java
Java SHA
Minimum Coins for Making a Given Value in Java
Eclipse Shortcuts Java
Empty Statement in Java
Java Program to Implement Two Stacks in an Array
Java Snippet
Longest Arithmetic Progression Sequence in Java
Types of Sockets in Java
Java Program to Add Digits Until the Number Becomes a Single Digit Number
Next Greater Number with Same Set of Digits in Java
Split the Number String into Primes in Java
Java Cron Expression
Huffman Coding Java
Java Snippet Class
Why Java is So Popular
Java Project idea
Java Web Development
Brilliant Numbers in Java
Sort Elements by Frequency in Java
Beautiful Array in Java
Moran Numbers in Java
Intersection Point of Two Linked List in Java
Sparse Number in Java
How to Check JRE Version
Java Programming Certification
Two Decimal Places Java
Eclipse Change Theme
Java how to Convert Bytes to Hex
Decagonal Numbers in Java
Java Binary to Hexadecimal Conversion
Java Hexadecimal to Binary Conversion
How to Capitalize the First Letter of a String in Java
Java &0XFF Example
Stream findFirst() Method in Java
Balanced Parentheses in Java
Caesar Cipher Program in Java
next() vs nextLine()
Java Split String by Comma
Spliterator in java 8
Tree Model Nodes in Jackson
Types of events in Java
Callable and Future in Java
How to Check Current JDK Version installed in Your System Using CMD
How to Round Double and Float up to Two Decimal Places in Java
Java 8 Multimap
Parallel Stream in Java
Java Convert Bytes to Unsigned Bytes
Java SFTP
Display List of TimeZone with GMT and UTC in Java
Binary Strings Without Consecutive Ones in Java
Convert IP to Binary in Java
Java Macro
Returning Multiple Values in Java
Centered Square Numbers in Java
ProcessBuilder in Java
How to Clear Java Cache
IntSummaryStatistics Class in Java
Java ProcessBuilder Example
Java Program to Delete a Directory
Java Program to Print Even Odd Using Two Threads
Java Variant
MessageDigest in Java
Alphabet Pattern in Java
Java Linter
Java Mod Example
Stone Game in Java
TypeErasure in Java
How to Remove substring from String in Java
Program to print a string in vertical in Java
How to Split a String between Numbers and Letters
String Handling in Java
Isomorphic String in Java
Java ImageIO Class
Minimum Difference Subarrays in Java
Plus One to Array Problem in Java
Unequal Adjacent Elements in Java
Java Parallel Stream Example
SHA Hashing in Java
How to make Java projects
Java Fibers
Java MD5 Hashing Example
Hogben Numbers in Java
Self-Descriptive Numbers in Java
Hybrid Inheritance in Java
Java IP Address (IPv4) Regex Examples
Converting Long to Date in JAVA
Java 17 new features
GCD of Different SubSequences in Java
Sylvester Sequence in Java
Console in Java
Asynchronous Call in Java
Minimum Window Substring in Java
Nth Term of Geometric Progression in Java
Coding Guidelines in Java
Couple Holding Hands Problem in Java
Count Ones in a Sorted binary array in Java
Ordered Pair in Java
Tetris Game in Java
Factorial Trailing Zeroes in Java
Java Assert Examples
Minimum Insertion To Form A Palindrome in Java
Wiggle Sort in Java
Java DOM
Java Exit Code 13
Java JFileChooser
What is LINQ
NZEC in Java
Box Stacking Problem
K Most Frequent Elements in Java
Parallel Programming in Java
How to Generate JVM Heap Memory Dump
Java Program to use Finally Block for Catching Exceptions
Count Login Attempts Java
Largest Independent Set in Java
Longest Subarray With All Even or Odd Elements in Java
Open and Closed Hashing in Java
DAO Class in Java
Kynea Numbers in Java
UTF in Java
Zygodromes in Java
ElasticSearch Java API
Form Feed in Java
Java Clone Examples
Payment Gateway Integration in Java
What is PMD
RegionMatches() Method in Java
Repaint() Method in Java
Serial Communication in Java
Count Double Increasing Series in A Range in Java
Longest Consecutive Subsequence in Java
Smallest Subarray With K Distinct Numbers in Java
String Sort Custom in Java
Count Number of Distinct Substrings in a String in Java
Display All Subsets of An Integer Array in Java
Digit Count in a Factorial Of a Number in Java
Valid Parentheses Problem in Java
DAO Class in Java
Median Of Stream Of Running Integers in Java
Arrow Operator in Java
Java Learning app
Create Preorder Using Postorder and Leaf Nodes Array
Display Leaf nodes from Preorder of a BST in Java
Unicodes for Operators in Java
XOR and XNOR operators in Java
AWS Lambda in Java
AWS Polly in Java
SAML in Java
SonarQube in Java
UniRest in Java
Override equals method in Java
Undo and Redo Operations in Java
Size of longest Divisible Subset in an Array in Java
Sort An Array According To The Set Bits Count in Java
Two constructors in one class in Java
Union in Java
What is New in Java 15
ART in Java
Definite Assignment in Java
Cast Operator in Java
Diamond operator in Java
Java Singleton Enum
Size of longest Divisible Subset in an Array in Java
Three-way operator | Ternary operator in Java
GoF Design Pattern Java
Java Programming Certification
Shorthand Operator in Java
What is new in Java 17
How to Find the Java Version in Linux
What is New in Java 12
Exception in Thread Main [Link] no line Found
How to reverse a string using recursion in Java
Java Program to Reverse a String Using Stack
Java Program to Reverse a String Using the Stack Data Structure
Reverse Middle Words of a String in Java
Sastry Numbers in Java
Sum of LCM in Java
Tilde Operator in Java
8 Puzzle problems in Java
Maximum Sum Such That No Two Elements Are Adjacent in Java
Reverse a String in Place in Java
Reverse a string Using a Byte array in Java
Reverse a String Using Java Collections
Reverse String with Special Characters in Java
get timestamp in java
How to convert file to hex in java
AbstractSet in java
List vs Set vs Map in Java
Birthday Problem in Java
How to Calculate the Time Difference Between Two Dates in Java
Number of Mismatching Bits in Java
Palindrome Permutation of a String in Java
Grepcode [Link]
How to add 24 hrs to date in Java
How to Change the Day in The Date Using Java
Java ByteBuffer Size
[Link]
Maximum XOR Value in Java
How to Add Hours to The Date Object in Java
How to Increment and Decrement Date Using Java
Multithreading Scenarios in Java
Switch case with enum in Java
Longest Harmonious Subsequence in Java
Count OR Pairs in Java
Merge Two Sorted Arrays Without Extra Space in Java
How to call a concrete method of abstract class in Java
How to create an instance of abstract class in Java
Java Console Error
503 error handling retry code snippets Java
Implementation Of Abstraction In Java
How to avoid thread deadlock in Java
Number of Squareful Arrays in Java
One-Time Password Generator Code In Java
Real-Time Face Recognition In Java
Converting Integer Data Type to Byte Data Type Using Typecasting in Java
How to Generate File checksum Value
Index Mapping (or Trivial Hashing) With Negatives allowed in Java
Shortest Path in a Binary Maze in Java
customized exception in Java
Difference between error and exception in Java
How to solve deprecated error in Java
Jagged Array in Java
CloneNotSupportedException in Java with Examples
Difference Between Function and Method in Java
Immutable List in Java
Nesting Of Methods in Java
How to Convert Date into Character Month and Year Java
How to Mock Lambda Expression in Java
How to Return Value from Lambda Expression Java
if Condition in Lambda Expression Java
Chained Exceptions in Java
Final static variable in Java
Java File Watcher
Various Operations on HashSet in Java
Word Ladder Problem in Java
Various Operations on Queue in Java
Various Operations on Queue Using Linked List in Java
Various Operations on Queue Using Stack in Java
Get Yesterday's Date from Localdate Java
Get Yesterday's Date by No of Days in Java
Advantages of Lambda Expression in Java 8
Cast Generic Type to Specific type Java
ConcurrentSkipListSet in Java
Fail Fast Vs. Fail-Safe in Java
Get Yesterday's Date in Milliseconds Java
Get Yesterday's Date Using Date Class Java
Getting First Date of Month in Java
Gregorian Calendar Java Current Date
How to Calculate Time Difference Between Two Dates in Java
How to Calculate Week Number from Current Date in Java
Keystore vs Truststore
Leap Year Program in Java
Online Java Compiler GDB
Operators in Java MCQ
Separators In Java
StringIndexOutOfBoundsException in Java
Anonymous Function in Java
Default Parameter in Java
Group by Date Code in Java
How to add 6 months to Current Date in Java
How to Reverse A String in Java Letter by Letter
Java 8 Object Null Check
Java Synchronized
Types of Arithmetic Operators in Java
Types of JDBC Drivers in Java
Unmarshalling in Java
Write a Program to Print Reverse of a Vowels String in Java
ClassNotFound Exception in Java
Null Pointer Exception in Java
Why Does BufferedReader Throw IOException in Java
Java Program to Add two Complex Numbers
Read and Print All Files From a Zip File in Java
Reverse an Array in Java
Right Shift Zero Fill Operator in Java
Static Block in Java
Accessor and Mutator in Java
Array of Class Objects in Java
Benefits of Generics in Java
Can Abstract Classes Have Static Methods in Java
ClassNotFoundException Java
Creating a Custom Generic Class in Java
Generic Queue Java
Getting Total Hours From 2 Dates in Java
How to add 2 dates in Java
How to Break a Date and Time in Java
How to Call Generic Method in Java
How to Increment and Decrement Date using Java
Java Class Methods List
Java Full Stack Developer
[Link]
Least Operator to Express Number in Java
Shunting Yard Algorithm in Java
Singleton Class in Java
Switch Case Java
Treeset Java Operations
Types of Logical Operators in Java
What is Cast Operator in Java
What is Jersey in Java
Alternative to Java Serialization
API Development in Java
Disadvantage of Multithreading in Java
Find the row with the maximum number of 1s
Generic Comparator in Java
Generic LinkedList in Java
Generic Programming in Java Example
How Can I Give the Default Date in The Array Java
How to Accept Date in Java
How to add 4 years to Date in Java
How to Check Date Equality in Java
How to Modify HTML File Using Java
Java 8 Multithreading Features
Java Abstract Class and Methods
Java Thread Dump Analyser
Process vs. Thread in Java
Reverse String Using Array in Java
Types of Assignment Operators in Java
Types of Bitwise Operators in Java
Union and Intersection Of Two Sorted Arrays In Java
Vector Operations Java
Java Books Multithreading
Advantages of Generics in Java
Arrow Operator Java
Generic Code in Java
Generic Method in Java Example
Getting a Range of Dates in Java
Getting the Day from a Date in Java
How Counter Work with Date Using Java
How to Add Date in Arraylist Java
How to Create a Generic List in Java
Java Extend Multiple Classes
Java Function
Java Generics Design Patterns
Why Are Generics Used in Java
XOR Binary Operator in Java
Check if the given string contains all the digits in Java
Constructor in Abstract Class in Java
Count number of a class objects created in Java
Difference Between Byte Code and Machine Code in Java
Java Program to Append a String in an Existing File
Main thread in Java
Store Two Numbers in One Byte Using Bit Manipulation in Java
The Knight's Tour Problem in Java
Business Board Problem in Java
Business Consumer Problem in Java
Buy as Much Candles as Possible Java Problem
Get Year from Date in Java
How to Assign Static Value to Date in Java
Java List Node
Java List Sort Lambda
Java Program to Get the Size of a Directory
Misc Operators in Java
Reverse A String and Reverse Every Alternative String in Java
Reverse a String in Java Using StringBuilder
Reverse Alternate Words in A String Java
Size of Empty Class in Java
Titniry Operation in Java
Triple Shift Operator in Java
Types of Conditional Operators in Java
View Operation in Java
What is Linked list Operation in Java
What is Short Circuit && And or Operator in Java
What is the & Operator in Java
Why to use enum in Java
XOR Bitwise Operator in Java
XOR Logical Operator Java
Compile-Time Polymorphism in Java
Convert JSON to Java Object Online
Difference between comparing String using == and .equals() method in Java
Difference Between Singleton Pattern and Static Class in Java
Difference Between Static and Non-Static Nested Class in Java
Getting Date from Calendar in Java
How to Swap or Exchange Objects in Java
Java Get Class of Generic Parameter
Java Interface Generic Parameter
Java Map Generic
Java NLP
Java Number Class
Java Program for Maximum Product Subarray
Java Program To Print Even Length Words in a String
Logger Class in Java
Manacher's Algorithm in Java
Mutable Class in Java
Online Java IDE
Package getImplementationVersion() method in Java with Examples
Set Default Close Operation in Java
Sorting a Java Vector in Descending Order Using Comparator
Types of Interfaces in Java
Understanding String Comparison Operator in Java
User-Defined Packages in Java
Valid variants of main() in Java
What is a Reference Variable in Java
What is an Instance in Java
What is Retrieval Operation in ArrayList Java
When to Use the Static Method in Java
XOR Operations in Java
7th Sep - Array Declaration in Java
7th Sep - Bad Operand Types Error in Java
7th Sep - Data Structures in Java
7th Sep - Generic Type Casting In Java
7th Sep - Multiple Inheritance in Java
7th Sep - Nested Initialization for Singleton Class in Java
7th Sep - Object in Java
7th Sep - Recursive Constructor Invocation in Java
7th Sep - Java Language / What is Java
7th Sep - Why is Java Platform Independent
7th Sep - Card Flipping Game in Java
7th Sep - Create Generic Method in Java
7th Sep - Difference between super and super() in Java with Examples
7th Sep - for loop enum Java
7th Sep - How to Convert a String to Enum in Java
7th Sep - Illustrate Class Loading and Static Blocks in Java Inheritance
7th Sep - Introduction To Java
7th Sep - Java Lambda foreach
7th Sep - Java Latest Version
7th Sep - Java Method Signature
7th Sep - Java Practice Programs
7th Sep - Java SwingWorker Class
7th Sep - [Link] class in Java With Examples
7th Sep - Largest Palindrome by Changing at Most K-digits in Java
7th Sep - Parameter Passing Techniques in Java with Examples
7th Sep - Reverse a String in Java Using a While Loop
7th Sep - Reverse a String Using a For Loop in Java
7th Sep - Short Circuit Operator in Java
7th Sep - Java 8 Stream API
7th Sep - XOR Operation on Integers in Java
7th Sep - XOR Operation on Long in Java
Array Programs in Java
Concrete Class in Java
Difference between Character Stream and Byte Stream in Java
Difference Between Static and non-static in Java
Different Ways to Convert [Link] to [Link] in Java
Find the Good Matrix Problem in Java
How Streams Work in Java
How to Accept Different Formats of Date in Java
How to Add Date in MySQL from Java
How to Find the Size of int in Java
How to Make a Field Serializable in Java
How to Pass an Array to Function in Java
How to Pass an ArrayList to a Method in Java
Implementing the Java Queue Interface
Initialization of local variable in a conditional block in Java
isnull() Method in Java
Java Array Generic
Java Program to Demonstrate the Lazy Initialization Non-Thread-Safe
Java Program to Demonstrate the Non-Lazy Initialization Thread-Safe
Java Static Field Initialization
Machine Learning Using Java
Mars Rover Problem in Java
Model Class in Java
Nested Exception Handling in Java
Program to Convert List to Stream in Java
Static Polymorphism in Java
Static Reference Variables in Java
Sum of Two Arrays in Java
What is Is-A-Relationship in Java
When to Use Vector in Java
Which Class cannot be subclassed in Java
Word Search Problem in Java
XOR Operation Between Sets in Java
Burger Problem in Java Game
Convert Set to List in Java
Floyd Triangle in Java
How to Call Static Blocks in Java
Interface Attributes in Java
Java Applications in the Real World
Java Concurrent Array
Java Detect Date Format
Java Interface Without Methods
Java Iterator Performance
Java Packet
Java Static Instance of Class
Java TreeMap Sort by Value
Length of List in Java
List of Checked Exceptions in Java
Message Passing in Java
Product Maximization Problem in Java
Terminal Operations in Java 8
Understanding Base Class in Java
Difference between Early Binding and Late Binding in Java
Collectors toCollection() in Java
Difference between ExecutorService execute() and submit() method in Java
Difference between Java and Core Java
Different Types of Recursions in Java
Initialize a static map in Java with Examples
Java APIs
Merge Sort Using Multithreading in Java
Why [Link](), [Link](), and [Link]() Methods are
Deprecated After JDK 1.1 Version
Circular Primes in Java
Difference Between poll() and remove() Method of a Queue
EvalEx Java: Expression Evaluation in Java
Exeter Caption Contest Java Program
FileInputStream finalize() Method in Java
Find the Losers of the Circular Game problem in Java
Finding the Differences Between Two Lists in Java
Finding the Maximum Points on a Line in Java
Get Local IP Address in Java
Handling "Handler dispatch failed" Nested Exception:
[Link] in Java
Harmonic Number in Java
How to Find the Percentage of Uppercase Letters, Lowercase Letters, Digits, and
Special Characters in a String Using Java
Interface Variables in Java
Java 8 Interface Features
Java Class Notation
Java Exception Messages Examples and Explanations
Java Package Annotation
Java Program to Find First Non-Repeating Character in String
Java Static Type Vs. Dynamic Type
Kaprekar Number in Java
Multitasking in Java
Niven Number in Java
Rhombus Pattern in Java
Shuffle an Array in Java
Static Object in Java
The Scope of Variables in Java
Toggle String in Java
Use of Singleton Class in Java
What is the Difference Between Future and Callable Interfaces in Java
Aggregate Operation in Java 8
Bounded Types in Java
Calculating Batting Average in Java
Compare Two LinkedList in Java
Comparison of Autoboxed Integer objects in Java
Count Tokens in Java
Cyclomatic Complexity in Java
Deprecated Meaning in Java
Double Brace Initialization in Java
Functional Interface in Java
How to prevent objects of a class from Garbage Collection in Java
Java Cast Object to Class
Java isAlive() Method
Java Line Feed Character
Java Program for Maximum Product Subarray
[Link] class in Java
Keytool Error [Link]
Matrix Diagonal Sum in Java
Number of Boomerangs Problem in Java
Sieve of Eratosthenes Algorithm in Java
Similarities Between Bastar and Java
Spring vs. Struts in Java
Switch Case in Java 12
The Pig Game in Java
Unreachable Code Error in Java
Who Were the Kalangs of Java
2048 Game in Java
Abundant Number in Java
Advantages of Applet in Java
Alpha-Beta Pruning Java
ArgoUML Reverse Engineering Java
Can Constructor be Static in Java
Can we create object of interface in Java
Chatbot Application in Java
Difference Between Component and Container in Java
Difference Between [Link] and [Link]
Find A Pair with Maximum Product in Array of Integers
Goal Stack Planning Program in Java
Half Diamond Pattern in Java
How to find trigonometric values of an angle in Java
How to Override tostring() method in Java
Inserting a Node in a Doubly Linked List in Java
Java 9 Immutable Collections
Java 9 Interface Private Methods
Java Convert Array to Collection
Java Transaction API
Methods to Take Input in Java
Parallelogram Pattern in Java
Power of a Number in Java
Reminder Program in Java
Sliding Window Protocol in Java
Static Method in Java
String Reverse in Java 8 Using Lambdas
Types of Threads in Java
What is thread safety in Java? How do you achieve it?
[Link] Virus Java 9
Java 8 Merge Two Maps with Same Keys
Java 8 StringJoiner, [Link](), and [Link]()
Java 9 @SafeVarargs Annotation Changes
Java 9 Stream API Improvements
Java 11 var in Lambda Expressions
Sequential Search Java
Thread Group in Java
User Thread Vs. Daemon Thread in Java
Collections Vs. Streams in Java
F in Java
Import statement in Java
init() Method in Java
Java Generics Jenkov
Ambiguity in Java
Benefits of Learning Java
Designing a Vending Machine in Java
Monolithic Applications in Java
Name Two Types of Java Program
Random Access Interface in Java
Rust Vs. Java
Types of Constants in Java
Execute the Main Method Multiple Times in Java
Find the element at specified index in a Spiral Matrix in Java
Find The Index of An Array Element in Java
Mark-and-Sweep Garbage Collection Algorithm in Java
Shadowing of Static Functions in Java
Straight Line Numbers in Java
Zumkeller Numbers in Java
Types of Layout Manager in Java
Virtual Threads in Java 21
Add Two Numbers Without Using Operator in Java
Automatic Type Promotion in Java
ContentPane Java
Difference Between findElement() and findElements() in Java
Difference Between Inheritance and Interfaces in Java
Difference Between Jdeps and Jdeprscan tools in Java
Find Length of String in Java Without Using Function
InvocationTargetException in Java
Java Maps to JSON
Key Encapsulation Mechanism API in Java 21
Placeholder Java
String Templates in Java 21
Why Java is Robust Language
Collecting in Java 8
containsIgnoreCase() Method in Java
Convert String to Biginteger In Java
Convert String to Map in Java
Define Macro in Java
Difference Between Lock and Monitor in Java Concurrency
Difference Between the start() and run() Methods in Java
Generalization and Specialization in Java
getChannel() Method in Java
How to Check Whether an Integer Exists in a Range with Java
HttpEntity in Java
Lock Framework Vs. Thread Synchronization in Java
Niven Number Program in Java
Passing Object to Method in Java
Pattern Matching for Switch in Java 21
Swap First and Last Digit of a Number in Java
Adapter Design Pattern in Java
Best Automation Frameworks for Java
Building a Search Engine in Java
Bytecode Verifier in Java
Caching Mechanism in Java
Comparing Two HashMap in Java
Cryptosystem Project in Java
Farthest from Zero Program in Java
How to Clear Linked List in Java
Primitive Data Type Vs. Object Data Type in Java
setBounds() Method in Java
Unreachable Code or Statement in Java
What is Architecture Neutral in Java
Difference between wait and notify in Java
Dyck Path in Java
Find the last two digits of the Factorial of a given Number in Java
How to Get an Environment Variable in Java
Java Program to open the command prompt and insert commands
JVM Shutdown Hook in Java
Semiprimes Numbers in Java
12 Tips to Improve Java Code Performance
Ad-hoc Polymorphism in Java
Array to String Conversion in Java
CloudWatch API in Java
Essentials of Java Programming Language
Extends Vs. Implements in Java
2d Array Sorting in Java
Aliquot Sequence in Java
Authentication and Authorization in Java
Cannot Find Symbol Error in Java
Compare Two Excel Files in Java
Consecutive Prime Sum Program in Java
Count distinct XOR values among pairs using numbers in range 1 to N
Difference Between Two Tier and Three Tier Architecture in Java
Different Ways of Reading a Text File in Java
Empty Array in Java
FCFS Program in Java with Arrival Time
Immutable Map in Java
K-4 City Program in Java
Kahn's algorithm for Topological Sorting in Java
Most Popular Java Backend Tools
Recursive Binary Search in Java
Set Intersection in Java
String Reverse Preserving White Spaces in Java
The Deprecated Annotation in Java
What is JNDI in Java
Backtracking in Java
Comparing Doubles in Java
Consecutive Prime Sum in Java
Finding Missing Numbers in an Array Using Java
Good Number Program in Java
How to Compress Image in Java Source Code
How to Download a File from a URL in Java
Passing an Object to The Method in Java
Permutation program in Java
Profile Annotation in Java
Scenario Based Questions in Java
Understanding Static Synchronization in Java
Types of Errors in Java
Abstract Factory Design Pattern in Java
Advantages of Kotlin Over Java
Advantages of Methods in Java
Applet Program in Java to Draw House with Output
Atomic Boolean in Java
Bitset Class in Java
Bouncy Castle Java
Chained Exception in Java
Colossal Numbers in Java
Compact Profiles Java 8
Convert Byte to Image in Java
Convert Set to Array in Java
Copy ArrayList to another ArrayList Java
Copy Data from One File to Another in Java
Dead Code in Java
Driver Class Java
EnumMap in Java
Farthest Distance of a 0 From the Centre of a 2-D Matrix in Java
How to Terminate a Program in Java
Instance Block in Java
Iterative Constructs in Java
Java 10 var Keyword
Java Games
Nested ArrayList in Java
Square Pattern in Java
String Interpolation in Java
Unnamed Classes and Instance Main Method in Java 21
What is difference between cacerts and Keystore in Java
Agile Principles Patterns and Practices in Java
Color Method in Java
Concurrent Collections in Java
Create JSON Node in Java
Difference Between Checkbox and Radio Button in Java
Difference Between Jdeps and Jdeprscan Tools in Java
Difference Between Static and Dynamic Dispatch in Java
Difference Between Static and Non-Static Members in Java
Error Java Invalid Target Release 9
Filedialog Java
String Permutation in Java
Structured Concurrency in Java
Uncaught Exception in Java
ValueOf() Method in Java
Virtual Thread in Java
Difference Between Constructor Overloading and Method Overloading in Java
Difference Between for loop and for-each Loop in Java
Difference Between Fork/Join Framework and ExecutorService in Java
Difference Between Local, Instance, and Static Variables in Java
Difference Between Multithreading and Multiprocessing in Java
Difference Between Serialization and Deserialization in Java
Difference Between Socket and Server Socket in Java
Advantages of Immutable Classes in Java
BMI Calculator Java
Code Coverage Tools in Java
How to Declare an Empty Array in Java
How To Resolve [Link] in Java
Java 18 Snippet Tag with Example
Object Life Cycle in Java
print() Vs. println() in Java
@SuppressWarnings Annotation in Java
Types of Cloning in Java
What is portable in Java
What is the use of an interpreter in Java
Abstract Syntax Tree (AST) in Java
Aliasing in Java
CRUD Operations in Java
Euclid-Mullin Sequence in Java
Frame Class in Java
Initializing a List in Java
Number Guessing Game in Java
Number of digits in N factorial to the power N in Java
Rencontres Number in Java
Skewed Binary Tree in Java
Vertical zig-zag traversal of a tree in Java
Wap to Reverse a String in Java using Lambda Expression
Concept of Stream in Java
Constraints in Java
Context Switching in Java
Dart Vs. Java
Dependency Inversion Principle in Java
Difference Between Containers and Components in Java
Difference Between CyclicBarrier and CountDownLatch in Java
Difference Between Shallow and Deep Cloning in Java
Dots and Boxes Game Java Source code
DRY Principle Java
How to get File type in Java
IllegalArgumentException in Java example
Is the main() method compulsory in Java
Java Paradigm
Lower Bound in Java
Method Binding in Java
Overflow and Underflow in Java
Padding in Java
Passing and Returning Objects in Java
Single Responsibility Principle in Java
ClosedChannelException in Java with Examples
How to Fix [Link] Connection refused connect in Java
[Link] in java with Examples
Selection Statement in Java
Difference Between Java 8 and Java 9
Difference Between Nested Class and Inner Class in Java
Difference Between OOP and POP in Java
Difference Between Static and Dynamic in Java
Difference Between Static Binding and Dynamic Binding in Java
Difference Between Variable and Constant in Java
Advantages of Generics in Java
Alternate Pattern Program in Java
Architecture Neutral in Java
AutoCloseable Interface in Java
BitSet Class in Java
Border Layout Manager in Java
Digit Extraction in Java
Dynamic Method Dispatch Java
Dynamic Variable in Java
How to Convert Double to string in Java
How to Convert Meter to Kilometre in Java
How to Install SSL Certificate in Java
How to Protect Java Source Code
How to Use Random Object in Java
Java Backward Compatibility
Java New String Class Methods from Java 8 to Java 17
Mono in Java
Object to int in Java
Predefined Streams in Java
Prime Factor Program in Java
Transfer Statements in Java
What is Interceptor in Java
Java Array Methods
[Link] class in Java
Reverse Level Order Traversal in Java
Working with JAR and Manifest files In Java
Alphabet Board Path Problem in Java
Composite Design Pattern Java
Default and Static Methods in Interface Java 8
Difference Between Constraints and Annotations in Java
Difference Between fromJson() and toJson() Methods of GSON in Java
Difference Between Java 8 and Java 11
Difference Between map() and flatmap() Method in Java 8
Difference Between next() and nextLine() Methods in Java
Difference Between orTimeout() and completeOnTimeOut() Methods in Java 9
Disadvantages of Array in Java
How Synchronized works in Java
How to Create a Table in Java
ID Card Generator Using Java
Introspection in JavaBeans
Java 15 Features
Java CLOB
Java Object Model
Java Tools and Command-List
Next Permutation Java
Number Guessing Game in Java
Object as Parameter in Java
Optimizing Java Code Performance
Pervasive Shallowness in Java
Sequenced Collections in Java 21
Stdin and Stdout in Java
Stream count() Function in Java
[Link]() Method in Java
Vertical Flip Matrix Problem in Java
Calling Object in Java
Characteristics of Constructor in Java
Counting Problem in Multithreading in Java
Creating Multiple Pools of Objects of Variable Size in Java
Default Exception in Java
How to Install Multiple JDK's in Windows
Differences Between Vectors and Arrays in Java
Duplicate Class Errors in Java
Example of Data Hiding in Java
Foreign Function and Memory APIs in Java 21
Generic Tree Implementation in Java
getSource() Method in Java
Giuga numbers in Java
Hessian Java
How to Connect Login Page to Database in Java
Difference between BlueJ and JDK 1.3
How to Solve Incompatible Types Error in Java
Java 8 Method References
Java 9 Try with Resources Improvements
Menu-Driven Program in Java
Mono Class in Java
Multithreading Vs. Asynchronous in Java
Nested HashMap in Java
Number Series Program in Java
Object Slicing in Java
Oracle Java
Passing and Returning Objects in Java
Print 1 to 100 Without Loop in Java
Remove elements from a List that satisfy given predicate in Java
Replace Element in Arraylist Java
Sliding Puzzle Game in Java
Strobogrammatic Number in Java
Web Methods in Java
Web Scraping Java
Window Event in Java
@Builder Annotation in Java
Advantages of Abstraction in Java
Advantages of Packages in Java
Bounce Tales Java Game Download
Breaking Singleton Class Pattern in Java
Building a Brick Breaker Game in Java
Building a Scientific Calculator in Java
Circle Program in Java
Class Memory in Java
Convert Byte to an Image in Java
Count Paths in Given Matrix in Java
Difference Between Iterator and ListIterator in Java with Example
Distinct Character Count Java Stream
EOFException in Java
ExecutionException Java 8
Generic Object in Java
How to Create an Unmodifiable List in Java
How to Create Dynamic SQL Query in Java
How to Return a 2D Array in Java
Java 8 [Link]() Method
Java setPriority() Method
Mutator Methods in Java
Predicate Consumer Supplier Java 8
Program to Generate CAPTCHA and Verify User Using Java
Random Flip Matrix in Java
System Class in Java
Types of Errors in Java
Vigenere Cipher Program in Java
Behavior-Driven Development (BDD) in Java
CI/ CD Tools for Java
cint in Java
Command Pattern in Java
CSV to List Java
Difference Between Java Servlets and CGI
Difference Between Multithreading Multitasking, and Multiprocessing in Java
Encoding Three Strings in Java
How to Import Jar File in Eclipse
Meta Class Vs. Class in Java
Meta Class Vs. Super Class in Java
Print Odd and Even Numbers by Two Threads in Java
Scoped value in Java
Upper-Bounded Wildcards in Java
Wildcards in Java
Zero Matrix Problem in Java
All Possible Combinations of a String in Java
Atomic Reference in Java
Final Method Overloading in Java| Can We Overload Final Methods
Constructor in Inheritance in Java
Design Your Custom Connection Pool in Java
How Microservices Communicate with Each Other in Java
How to Convert String to Timestamp in Java
Java 10 Collectors Methods
Java 21
Java and Apache OpenNLP
Java Deep Learning
Java Iterator Vs. Listiterator Vs. Spliterator
Pure Functions in Java
Use of Constructor in Java | Purpose of Constructor in Java
Implement Quintet Class with Quartet Class in Java using JavaTuples
Java Best Practices
Efficiently Reading Input For Competitive Programming using Java 8
Length of the longest substring without repeating characters in Java
Advantages of Inner Class in Java
AES GCM Encryption Java
Array Default Values in Java
Copy File in Java from one Location to Another
Creating Templates in Java
Different Packages in Java
How to Add Elements to an Arraylist in Java Dynamically
How to Add Splash Screen in Java
How to Calculate Average Star Rating in Java
Immutable Class with Mutable Object in Java
Java instanceOf() Generics
Set Precision in Java
Snake Game in Java
Tower of Hanoi Program in Java
Two Types of Streams Offered by Java
Uses of Collections in Java
Additive Numbers in Java
Association Vs. Aggregation Vs. Composition in Java
Covariant and Contravariant Java
Creating Immutable Custom Classes in Java
mapToInt() in Java
Methods of Gson in Java
Server Socket in Java
Check String Are Permutation of Each Other in Java
Containerization in Java
Difference Between Multithreading and Multiprogramming in Java
Flyweight Design Pattern
HMAC Encryption in Java
How to Clear Error in Java Program
Strobogrammatic Number in Java
5 Types of Java
Design a Job Scheduler in Java
Elements of Java Programming
Generational ZCG in Java 21
How to Print Arraylist Without Brackets Java
How to Solve Incompatible Types Error in Java
Interface Vs. Abstract Class After Java 8
Java 9 Optional Class Improvements
Number of GP sequence Problem in Java
Pattern Matching for Switch
Range Addition Problem in Java
Swap Corner Words and Reverse Middle Characters in Java
Kadane's Algorithm in Java
Capture the Pawns Problem in Java
Compact Profiles Java 8
Find Pair With Smallest Difference in Java
How to pad a String in Java
When to use Serialization and Externalizable Interface
Which Component is responsible to run Java Program
Difference Between Java and Bastar
Difference Between Static and Instance Methods in Java
Difference Between While and Do While loop in Java
Future Interface in Java
Invert a Binary tree in Java
Java Template Engine
KeyValue Class in JavaTuples
Quantifiers in Java
Swapping Pairs of Characters in a String in Java
Version Enhancements in Exception Handling introduced in Java SE 7
Find all Palindromic Sub-Strings of a given String in Java
Find if String is K-Palindrome or not in Java
Count Pairs from an Array with Even Product of Count of Distinct Prime Factor in
Java
Find if an Array of Strings can be Chained to form a Circle in Java
Find largest factor of N such that NF is less than K in Java
Lexicographically First Palindromic String in Java
LinkedTransferQueue removeAll() method in Java with Examples
Next Smallest Palindrome problem in Java
Why Java is not a Purely Object-Oriented Language
Count all Distinct Pairs with difference Equal to K in Java
Count Pairs formed by Distinct Element Sub-Arrays in Java
Even numbers at even index and odd numbers at odd index in Java
LinkedTransferQueue retainAll() method in Java with Examples
LinkedTransferQueue tryTransfer() method in Java with Examples
Number of Equal Count Substrings in Java
Check if a given string is Even-Odd Palindrome or not in Java
Check if given String is Pangram or not in Java
Convert a List of String to a comma separated String in Java
Duration minusMinutes(long) method in Java with Examples
Insert a String into another String in Java
Java Collections checkedQueue() Method with Examples
String Literal Vs String Object in Java
ChoiceFormat applyPattern() method in Java with Examples
ChoiceFormat format() method in Java with Examples
ChoiceFormat getFormats() method in Java with Examples
ChoiceFormat hashCode() method in Java with Examples
ChoiceFormat parse() method in Java with Examples
CompositeName get() method in Java with Examples
Difference Between Package and Interface in Java
DoubleFunction Interface in Java with Examples
ThaiBuddhistDate now(Clock) method in Java with Example
ToIntFunction Interface in Java with Examples
How to Make Object Serializable in Java
Java Program to Check if Two Words Are Present in a String
Java Program to Generate Random Hexadecimal Bytes
ToIntBiFunction Interface in Java with Examples
AbstractCollection addAll() Method in Java with Examples
Checking if Two Words Are Present in a String in Java
DoubleAdder intValue() method in Java with Examples
DoubleConsumer Interface in Java with Examples
Generate Random Numbers Using Middle Square Method in Java
How to Write Robust Programs with the Help of Loops in Java
Implementing Sparse Vector in Java
[Link] class with Examples
[Link] class with Examples
[Link] interface in Java with Examples
[Link] interface in Java with Examples
LongConsumer Interface in Java with Examples
[Link]() Method in Java with Examples
ToLongBiFunction Interface in Java with Examples
10 Ways to Create a Stream in Java
ChoiceFormat equals() method in Java with Examples
How to Check if a String contains only ASCII in Java
How to set the TLS version in Java
IntSummaryStatistics getCount() method in Java with Examples
IntSummaryStatistics getMax() method in Java with Examples
IntSummaryStatistics getMin() method in Java with Examples
IntSummaryStatistics getSum() method in Java with Examples
Java Generics to Code Efficiently in Competitive Programming
Java Program to Extract Content from a PDF
Java Program to Print Mirror Upper Star Triangle Pattern
Java Program to Print Spiral Pattern of Numbers
[Link] interface with Examples
[Link] interface in Java with Examples
[Link] class with Examples
[Link] class with Examples
Parallel vs Sequential Stream in Java
Restrictions on Generics in Java
Word Count Using Multithreading in Java
Can we make the main() thread as daemon in Java
How to Create a File with a Specific charset in Java
How to Create a File with a Specific File Attribute in Java
How to Create a File with a Specific Owner and Group in Java
How to Create and Manipulate a Memory-Mapped File in Java
Maximum XOR for Each Query in Java
Represent KN as The Sum of Exactly N numbers in Java
Spell Checker in Java
Arranging Coin Problem in Java
Beautiful Path Code in Java
Boolean Evaluation in Java
How to make non daemon thread as daemon in Java
Java Program to Convert Boolean to Integer
Java Program to Represent Linear Equations in Matrix Form
Null Object Design Pattern Java
Program for Derivative of a Polynomial
Program to Emulate N Dice roller in Java
String Compression Problem in Java
Divide large number represented as string in Java
Java tricks for Competitive Programming (for Java 8)
Largest integers with sum of setbits at most K in Java
Java default Keyword
Longest Happy String in Java
Maximum sum of a Subarray with prime integers in Java
Minimum Swaps to Arrange a Binary Grid in Java
Array Partition Problem in Java
Atomic Vs. Volatile in Java
Difference Between Java and .Net
Difference Between Java and JDK
File Descriptor Class in Java
File Permissions in Java
Finalizer Chaining in Java
Find the N-th Value After K Seconds in Java
FloatBuffer allocate() method in Java With Examples
FloatBuffer clear() methods in Java with Examples
FloatBuffer duplicate() method in Java with Examples
FloatBuffer equals() method in Java with examples
FloatBuffer put() methods in Java with Examples
Horizontal Flip Matrix Problem in Java
Lifetime of Variables in Java
Matrix Max Sum Path Problem in Java
Method and Block Synchronization in Java
Number Complement Problem in Java
OffSetDate Time getDayOfMonth() method in Java with examples
OffsetDateTime format() method in Java with examples
OffsetDateTime getOffset() method in Java with examples
Rotate a given Matrix in Java in Java
Solving Sudoku Using Multithreading in Java
Spiral Matrix Problem in Java
Third Maximum Number Problem in Java
Valid Number Problem in Java
Valid Square Problem in Java
Atomic Vs. Synchronized in Java
Blank Final in Java
Boggle Search Problem in Java
Custom Classes in Java
Difference Between [Link], [Link] and [Link] in Java
FloatBuffer mark() methods in Java with Examples
FloatBuffer rewind() methods in Java with Examples
Generate Random String of Given Size in Java
Image Processing in Java: Get and Set Pixels
Java [Link]() Method
Interesting Facts About Null in Java
Iterator Vs. foreach in Java
Java Numeric Promotion in Conditional Expression
Java Quantifiers
Largest Square Matrix Problem in Java
Object Reference Equality
Reflect Array in Java
Stream mapToDouble() in Java with Examples
Stream noneMatch() Method in Java with Examples
Stream skip() Method in Java With Examples
Sum of Numbers with Units Digit K in Java
Using _ (underscore) as Variable Name in Java
AbstractSequentialList clear() method in Java with Example
AtomicIntegerArray set() method in Java with Examples
AtomicIntegerArray toString() method in Java with Examples
AtomicLongArray set() method in Java with Examples
Can We Extend Final Method in Java
Check If the Given Two Matrices Are Mirror Images of One Another in Java
Convert A Mobile Numeric Keypad Sequence to Equivalent Sentence
Difference Between [Link]() and [Link]() Function in Java
Difference Between [Link]() and [Link]() in Java
Do We Need Forward Declarations in Java
Few Tricky Programs in Java
Find Largest Rectangle in Matrix Java
FloatBuffer flip() methods in Java with Examples
FloatBuffer get() methods in Java with Examples
How Does Default Virtual Behavior Differ in C++ and Java
How to Make Java Regular Expression Case Insensitive in Java
Image Processing in Java
Image Processing in Java: Colored Image to Negative Image Conversion
Implementing our Own Hash Table with Separate Chaining in Java
Island of Isolation in Java
Java Community Process
Java Program to Cyclically Permute the Elements of an Array
Java Program to Find Two Elements Whose Sum is Closest to Zero
Java Program to Perform Message Encoding Using Matrix Multiplication
Maximum Score of a Good Subarray in Java
new Operator Vs. newInstance() Method in Java
Java Object getClass() Method
Package getPackages() method in Java with Examples
Redirecting [Link]() Output to a File in Java
Abstract Syntax Tree (AST) Vs. Parse Tree
Catching Base and Derived Classes as Exceptions in Java
Create Java temp File
DoubleBuffer array() method in Java With Examples
DoubleBuffer clear() methods in Java with Examples
DoubleBuffer compact() method in Java With Examples
DoubleBuffer order() methods in Java with Examples
Effectively Final Variable in Java with Examples
Euclidean Algorithm in Java
Find all Primes to a Given Natural Number Using the Sieve of Eratosthenes
Method
Find Common Prime Divisors in Java
Find Longest Substring Containing Exactly K-Vowels in Java
Find the Longest Common Prefix using Word-by-Word Matching in Java
Find the Longest Substring Consisting of Vowels Using Binary Search in Java
Find the Longest Substring Having K Distinct Vowels in Java
Image Processing in Java-Comparison of Two Images - Javatpoint
Image Processing in Java - Creating a Random Pixel Image
Image Processing in Java-Brightness Enhancement
Image Processing in Java: Coloured Image to Grayscale Image Conversion
Image Processing in Java: Converting Colored Images to Red, Green, and Blue
Images
Image Processing in Java-Changing Orientation of an Image
Image Processing in Java - Contrast Enhancement
Volatile Keyword in Java
Java Optional Class orElseThrow() Method
Java Precondition
Java Program to Find the Minimum Distance Between Array Elements
Java Program to Find the Smallest Positive Number Missing from an Unsorted
Array
Java Program to Implement Associative Array
Java Program to Increment All Elements of an Array by One
Java Program to Maximize Count of Substrings Containing at Least 1 Vowel and
1 Consonant
Java Program to Merge Two Arrays Without Extra Space
Java Program to Move All Zeros to the Start of an Array
Java Program to Print Odd Elements at Even Index
Java Program to Print Odd Elements at Odd Index
Minimum Suffix Flips in Java
Number of Restricted Paths From First to Last Node in Java
Swapping Two Variables in One Line in Java
Codility Passing Car Problem in Java
"Cover ""Manhattan Skyline"" Using The Minimum Number of Rectangles"
Find the Longest Common Prefix Using Binary Search in Java
Find the Longest Sequence of Zeros in the Binary Representation of an Integer
Find the Minimum Shift for the Longest Common Prefix in Java
Find The Smallest Positive Integer That Does Not Occur in A Given Sequence
Image Processing in Java- Colored Image to Sepia Image Conversion
Image Processing in Java - Watermarking an Image
Java Performance Optimization: Tips and Techniques
Toeplitz matrix in Java
What is a Memory-Mapped File in Java
ASCII
James Gosling : The Father of Java
Core Java MCQ
Java Date Class
[Link]
after()
before()
clone()
compareTo()
equals()
getTime()
hashCode()
setTime()
from()
getDate()
getDay()
getHours()
toInstant()
toString()
getMinutes()
getYear()
parse()
setDate()
setHours()
setMinutes()
getMonth()
getSeconds()
getTimezoneOffset()
toGMTString()
toLocaleString()
utc()
Java ListIterator Class
Java ListIterator
add()
hasNext()
hasPrevious()
nextIndex()
next()
previousIndex()
previous()
remove()
set()
Java NIO Tutorial
Java NIO
NIO Components
NIO Package
NIO vs. IO
NIO Channels
NIO Buffers
NIO Scatter/Gather
NIO Data Transfer
NIO Selector
NIO SocketChannel
NIO ServerSocketChannel
NIO Pipe
NIO CharSet
NIO Encode/Decode
NIO Channels FileLock
HttpURLConnection
Java HttpURLConnection
disconnect()
getErrorStream()
getFollowRedirects()
getHeaderField()
getResponseCode()
getResponseMessage()
setAuthenticator()
setFollowRedirects()
Java Deque
Java Deque
add()
addAll()
addFirst()
addLast()
contains()
descendingIterator()
element()
getFirst()
getLast()
iterator()
offer()
offerFirst()
offerLast()
peek()
peekFirst()
peekLast()
poll()
pollFirst()
pollLast()
pop()
push()
remove()
removeFirst()
removeLast()
removeFirstOccurrence()
removeLastOccurrence()
size()
Java HttpCookie Class
Java HttpCookie
clone()
domainMatches()
equals()
getComment()
getCommentURL()
getDiscard()
getDomain()
getMaxAge()
getName()
getPath()
getPortList()
getSecure()
getValue()
parse()
setComment()
setCommentURL()
setDiscard()
setDomain()
setHttpOnly()
setMaxAge()
Java URL class
class getDefaultPort()
equals()
getAuthority()
getContent()
getFile()
getHost()
getPath()
getPort()
getProtocol()
getRef()
getUserInfo()
hashCode()
openConnection()
sameFile
toExternalfile()
toString()
toURI()
Java List Methods
containsAll()
equals()
get()
hashCode()
indexOf()
isEmpty()
size()
sort()
spliterator()
sublist()
toArray()
Java Vector class
add()
addAll()
addElement()
capacity()
clear()
clone()
containsAll()
contains()
copyInto()
elements()
ensureCapacity()
equals()
firstElement()
forEach()
hashCode()
elementAt()
get()
indexOf()
insertElementAt()
isEmpty()
iterator()
lastElement()
lastIndexOf()
removeAllElements()
removeAll()
removeElementAt()
removeElement()
remove()
replaceAll()
retainAll()
removeRange()
setElementAt()
set()
setSize()
size()
sort()
spliterator()
subList()
toString()
trimToSize()
listIterator()
toArray()
Java Collection Methods
add()
addAll()
clear()
contains()
containsAll()
equals()
hashCode()
isEmpty()
iterator()
remove()
removeAll()
removeIf()
retainAll()
size()
spliterator()
toArray()
Java Socket Class
Socket Class
bind()
close()
connect()
get00BInline()
getChannel()
getInetAddress()
getKeepAlive()
getLocalPort()
getLocalSocketAddress()
getPort()
getReceiveBufferSize()
getRemoteSocketAddress()
getReuseAddress()
getSendBufferSize()
getSoLinger()
getSoTimeout()
getTcpNoDelay()
getTrafficClass()
isBound()
isClosed()
isConnected()
isInputShutdown()
isOutputShutdown()
sendUrgentData()
setKeepAlive()
setOOBInline()
setTrafficClass()
shutdownInput()
shutdownOutput()
setSoLinger()
setSoTimeout()
setTcpNoDelay()
getInputStream()
getOutputStream()
setReceiveBufferSize()
setReuseAddress()
setSendBufferSize()
toString()
Java Executors
Java Executors
callable()
defaultThreadFactory()
newCachedThreadPool()
newFixedThreadPool()
newScheduledThreadPool()
newSingleThreadExecutor()
newWorkStealingPool()
privilegedThreadFactory()
Java Integer Class
Java Integer parseInt() Method
Java Integer Class
Java Integer bitCount() method
Java Integer byteValue() method
Java Integer compare() method
Java Integer compareTo() method
Java Integer compareUnsigned() Method
Java Integer decode() method
Java Integer divideUnsigned() Method
Java Integer doubleValue() method
Java Integer equals() Method
Java Integer floatValue() Method
Java Integer hashCode() Method
Java Integer highestOneBit() Method
Java Integer intValue() Method
Java Integer longValue() Method
Java Integer lowestOneBit() Method
Java Integer max() Method
Java Integer min() Method
Java Integer numberOfLeadingZeros() Method
Java Integer numberOfTrailingZeros() Method
Java Integer parseUnsignedInt() Method
Java Integer remainderUnsigned() Method
Java Integer reverseBytes Method
Java Integer reverse() Method
Java Integer rotateLeft() Method
Java Integer rotateRight() Method
Java Integer shortValue() Method
Java Integer signum() Method
Java Integer sum() Method
Java Integer toBinaryString() Method
Java Integer toHexString() Method
Java Integer toOctalString() Method
Java Integer toString() Method
Java Integer toUnsignedLong() Method
Java Integer toUnsignedString() Method
Java IdentityHashMap
Java IdentityHashMap values() method
Java IdentityHashMap size() method
Java IdentityHashMap remove() method
Java IdentityHashMap putAll() method
Java IdentityHashMap put() method
Java IdentityHashMap keySet() method
Java IdentityHashMap isEmpty() method
Java IdentityHashMap hashCode() method
Java IdentityHashMap get() method
Java IdentityHashMap equals() method
Java IdentityHashMap entrySet() method
Java IdentityHashMap containsValue() method
Java IdentityHashMap containsKey() method
Java IdentityHashMap clone() method
Java IdentityHashMap clear() method
Java ArrayBlockingQueue
Java ArrayBlockingQueue drainTo() Method
Java ArrayBlockingQueue Class
Java ArrayBlockingQueue add() Method
Java ArrayBlockingQueue clear() Method
Java ArrayBlockingQueue contains() Method
Java ArrayBlockingQueue forEach() Method
Java ArrayBlockingQueue iterator() Method
Java ArrayBlockingQueue offer() Method
Java ArrayBlockingQueue peek() Method
Java ArrayBlockingQueue poll() Method
Java ArrayBlockingQueue put() Method
Java ArrayBlockingQueue removeAll() Method
Java ArrayBlockingQueue remainingCapacity() Method
Java ArrayBlockingQueue remove() Method
Java ArrayBlockingQueue removeIf() Method
Java ArrayBlockingQueue retainAll() Method
Java ArrayBlockingQueue size() Method
Java ArrayBlockingQueue Spliterator() Method
Java ArrayBlockingQueue take() Method
Java ArrayBlockingQueue toString() Method
Java ArrayBlockingQueue toArray() Method
Java Timestamp
Java Timestamp Class
Java Timestamp after() Method
Java Timestamp before() Method
Java Timestamp compareTo() Method
Java Timestamp equals() Method
Java Timestamp from() Method
Java Timestamp getNanos() Method
Java Timestamp getTime() Method
Java Timestamp hashCode() Method
Java Timestamp setNanos() Method
Java Timestamp setTime() Method
Java Timestamp toInstant() Method
Java Timestamp toLocalDateTime() Method
Java Timestamp toString() Method
Java Timestamp valueOf() Method
Java Spliterator
Java Spliterator
Java Spliterator characteristics() Method
Java Spliterator estimateSize() Method
Java Spliterator forEachRemaining() Method
Java Spliterator getComparator() Method
Java Spliterator getExactSizeIfKnown() Method
Java Spliterator hasCharacteristics() Method
Java Spliterator tryAdvance() Method
Java Spliterator trySplit() Method
Java Bitset
Java BitSet flip() method
Java BitSet xor() method
Java BitSet valueOf() method
Java BitSet toString() method
Java BitSet toLongArray() method
Java BitSet toByteArray() method
Java BitSet stream() method
Java BitSet size() method
Java BitSet set() method
Java BitSet previousSetBit() method
Java BitSet previousClearBit() method
Java BitSet or() method
Java BitSet nextSetBit() method
Java BitSet nextClearBit() method
Java BitSet length() method
Java BitSet isEmpty() method
Java BitSet intersects() method
Java BitSet hashCode() method
Java BitSet get() method
Java BitSet equals() method
Java BitSet clone() method
Java BitSet cardinality() method
Java BitSet clear() method
Java BitSet andNot() method
Java BitSet and() method
Java Instant
Java Instant query() method
Java Instant compareTo() method
Java Instant plusSeconds() method
Java Instant plusNanos() method
Java Instant plusMillis() method
Java Instant atOffset() method
Java Instant ofEpochSecond() method
Java Instant ofEpochMilli() method
Java Instant now() method
Java Instant minusSeconds() method
Java Instant minusNanos() method
Java Instant minusMillis() method
Java Instant minus() method
Java Instant isSupported() method
Java Instant isBefore() method
Java Instant isAfter() method
Java Instant hashCode() method
Java Instant getNano() method
Java Instant get() method
Java Instant getLong() method
Java Instant getEpochSecond() method
Java Instant equals() method
Java Instant atZone() method
Java Instant adjustInto() method
← prevnext →
JDBC RowSet
An instance of RowSet is the Java bean component because it has properties and Java bean notification mechanism
RowSet facilitates a mechanism to keep the data in tabular form. It happens to make the data more flexible as w
The connection between the data source and the RowSet object is maintained throughout its life cycle. The RowS
component-based such as JavaBeans, with the standard set of properties and the mechanism of event notification.
It was in the JDBC 2.0, the support for the RowSet was introduced using the optional packages. But the impleme
the JDBC RowSet Implementations Specification (JSR-114) by the Sun Microsystems that is being present in the
The implementation classes of the RowSet interface are as follows:
o JdbcRowSet
o CachedRowSet
o WebRowSet
o JoinRowSet
o FilteredRowSet
Let's see how to create and execute RowSet.
JdbcRowSet rowSet = [Link]().createJdbcRowSet();
[Link]("jdbc:oracle:thin:@localhost:1521:xe");
[Link]("system");
[Link]("oracle");
[Link]("select * from emp400");
[Link]();
It is the new way to get the instance of JdbcRowSet since JDK 7.
Advantage of RowSet
The advantages of using RowSet are given below:
1. It is easy and flexible to use.
2. It is Scrollable and Updatable by default.
Example of JdbcRowSet
Let's see the simple example of JdbcRowSet without event handling code.
FileName: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. [Link]("[Link]");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = [Link]().createJdbcRowSet();
16. [Link]("jdbc:oracle:thin:@localhost:1521:xe");
17. [Link]("system");
18. [Link]("oracle");
19.
20. [Link]("select * from emp400");
21. [Link]();
22.
23. while ([Link]()) {
24. // Generating cursor Moved event
25. [Link]("Id: " + [Link](1));
26. [Link]("Name: " + [Link](2));
27. [Link]("Salary: " + [Link](3));
28. }
29.
30. }
31. }
The output is given below:
Id: 55
Name: Om Bhim
Salary: 70000
Id: 190
Name: abhi
Salary: 40000
Id: 191
Name: umesh
Salary: 50000
Example of JDBC RowSet with Event Handling
To perform event handling with JdbcRowSet, you need to add the instance of RowSetListener in the addRowSetL
The RowSetListener interface provides 3 method that must be implemented. They are as follows:
1. public void cursorMoved(RowSetEvent event);
2. public void rowChanged(RowSetEvent event);
3. public void rowSetChanged(RowSetEvent event);
Let's write the code to retrieve the data and perform some additional tasks while the cursor is moved, the cursor i
event handling operation can't be performed using ResultSet, so it is preferred now.
FileName: [Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
10. public class RowSetExample {
11. public static void main(String[] args) throws Exception {
12. [Link]("[Link]");
13.
14. //Creating and Executing RowSet
15. JdbcRowSet rowSet = [Link]().createJdbcRowSet();
16. [Link]("jdbc:oracle:thin:@localhost:1521:xe");
17. [Link]("system");
18. [Link]("oracle");
19.
20. [Link]("select * from emp400");
21. [Link]();
22.
23. //Adding Listener and moving RowSet
24. [Link](new MyListener());
25.
26. while ([Link]()) {
27. // Generating cursor Moved event
28. [Link]("Id: " + [Link](1));
29. [Link]("Name: " + [Link](2));
30. [Link]("Salary: " + [Link](3));
31. }
32.
33. }
34. }
35.
36. class MyListener implements RowSetListener {
37. public void cursorMoved(RowSetEvent event) {
38. [Link]("Cursor Moved...");
39. }
40. public void rowChanged(RowSetEvent event) {
41. [Link]("Cursor Changed...");
42. }
43. public void rowSetChanged(RowSetEvent event) {
44. [Link]("RowSet changed...");
45. }
46. }
The output is as follows:
Cursor Moved...
Id: 55
Name: Om Bhim
Salary: 70000
Cursor Moved...
Id: 190
Name: abhi
Salary: 40000
Cursor Moved...
Id: 191
Name: umesh
Salary: 50000
Cursor Moved...
Next TopicJDBC New Features
← prevnext →
Advertisement
Learn Important Tutorial
Python
Java
Javascript
HTML
Database
PHP
C++
React
[Link] / MCA
DBMS
Data Structures
DAA
Operating System
Computer Network
Compiler Design
Computer Organization
Discrete Mathematics
Ethical Hacking
Computer Graphics
Web Technology
Software Engineering
Cyber Security
Automata
C Programming
C++
Java
.Net
Python
Programs
Control System
Data Warehouse
Preparation
Aptitude
Reasoning
Verbal Ability
Interview Questions
Company Questions