Java Unit-3 Lecture-22,23 24 (5 Files Merged)
Java Unit-3 Lecture-22,23 24 (5 Files Merged)
Java Unit-3 Lecture-22,23 24 (5 Files Merged)
2
AWT, SWING, LAYOUT
Java AWT Tutorial
•Java AWT (Abstract Window Toolkit) is an API to develop GUI or
window-based applications in java.
•AWT is heavyweight i.e. its components are using the resources of OS.
•The java.awt package provides classes for AWT api such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List etc.
Java AWT Hierarchy
Cont..
Container
The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class
are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It
can have other components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It
can have other components like button, textfield etc.
Useful Methods of Component class
Creating Frame
Create a Frame class object:
Frame f= new Frame();
Event object
Event handling
methods
ActionEvent
actionPerformed(..)
Button ActionListener
Steps to perform Event Handling
Following steps are required to perform event handling:
Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
Button
public void addActionListener(ActionListener a){}
MenuItem
public void addActionListener(ActionListener a){}
TextField
public void addActionListener(ActionListener a){}
public void addTextListener(TextListener a){}
Cont..
TextArea
public void addTextListener(TextListener a){}
Checkbox
public void addItemListener(ItemListener a){}
Choice
public void addItemListener(ItemListener a){}
List
public void addActionListener(ActionListener a){}
public void addItemListener(ItemListener a){}
Java ActionListener Interface
• The Java ActionListener is notified whenever you click on the button or
menu item. It is notified against ActionEvent.
• The ActionListener interface is found in java.awt.event package.
• It has only one method: actionPerformed().
• actionPerformed() method
• The actionPerformed() method is invoked automatically whenever
you click on the registered component.
• public abstract void actionPerformed(ActionEvent e);
Java ActionListener Interface(cont..)
How to write ActionListener
• The common approach is to implement the ActionListener. If you
implement the ActionListener class, you need to follow 3 steps:
18
Java Swing
JAVA Swing
•Java Swing is a part of Java Foundation Classes (JFC) that is used to
create window-based applications.
• It is built on the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
•Unlike AWT, Java Swing provides platform-independent and lightweight
components.
•The javax.swing package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.
Difference between AWT and Swing
Hierarchy of Java Swing classes
Simple Java Swing Example
import javax.swing.*;
public class FirstSwingExample
{
public static void main(String[] args)
{
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
Layout
Java LayoutManagers
• The LayoutManagers are used to arrange components in a particular
manner.
• LayoutManager is an interface that is implemented by all the classes
of layout managers.
• There are following classes that represents the layout managers:
java.awt.BorderLayout
java.awt.FlowLayout
java.awt.GridLayout
java.awt.CardLayout
java.awt.GridBagLayout
javax.swing.BoxLayout
javax.swing.GroupLayout
javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five
regions: north, south, east, west and center. Each region (area)
may contain one component only. It is the default layout of
frame or window. The BorderLayout provides five constants for
each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
JFrame f; f.add(b4);
MyGridLayout(){ f.add(b5);
f.setSize(300,300);
JButton b1=new JButton("1"); f.setVisible(true);
JButton b2=new JButton("2"); }
JButton b3=new JButton("3"); public static void main(String[] args) {
JButton b4=new JButton("4"); new MyFlowLayout();
}
JButton b5=new JButton("5");
}
Summary
. Discussed about AWT.
. Discussed about Swing components and container.
. Discussed different layouts.
32
Home Work
Q1. Difference between Applet and Swing?
33
References
Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .
34
THANK YOU
For queries
Email: kushagra.e13465@cumail.in
UNIVERSITY INSTITUTE OF ENGINEERING
DEPARTMENT OF AIT - CSE
Bachelor of Engineering (CSE)
Programming in Java (21CSH-244)
By: Kushagra Agrawal (E13465)
2
JavaBean
JAVA Beans
A JavaBean is a Java class that should follow the following conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties, known as getter and setter
methods.
Why use JavaBean?
• According to Java white paper, it is a reusable software component.
• A bean encapsulates many objects into one object so that we can access
this object from multiple places. Moreover, it provides easy
maintenance.
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}
6
JavaBean Properties
• A JavaBean property is a named feature that can be accessed by the user of the object.
The feature can be of any Java data type, containing the classes that you define.
• A JavaBean property may be read, write, read-only, or write-only. JavaBean features are
accessed through two methods in the JavaBean's implementation class:
1. getPropertyName ()
For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.
7
Advantages of JavaBean
The following are the advantages of JavaBean:/p>
• The JavaBean properties and methods can be exposed to another application.
• It provides an easiness to reuse the software components.
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:
• JavaBeans are mutable. So, it can't take advantages of immutable objects.
• Creating the setter and getter method for each property separately may lead to the
boilerplate code.
8
Summary
. Discussed about Java Beans.
9
Home Work
Q1. Difference between Java Bean and Bean?
10
References
Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .
11
THANK YOU
For queries
Email: kushagra.e13465@cumail.in
UNIVERSITY INSTITUTE OF ENGINEERING
DEPARTMENT OF AIT - CSE
Bachelor of Engineering (CSE)
Programming in Java (21CSH-244)
By: Kushagra Agrawal (E13465)
2
JAVA SERVLET
Servlets
• Servlet technology is used to create a web application
(resides at server side and generates a dynamic web page).
• There are many interfaces and classes in the Servlet API such
as Servlet, GenericServlet, HttpServlet, ServletRequest,
ServletResponse, etc.
What is a Servlet?
• Servlet is a technology which is used to create a web application.
• Servlet is an API that provides many interfaces and classes including
documentation.
• Servlet is an interface that must be implemented for creating any
Servlet.
• Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any requests.
• Servlet is a web component that is deployed on the server to create a
dynamic web page.
CGI vs Servlet
7
Static website Vs Dynamic website
9
HTTP (Hyper Text Transfer Protocol)
• The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative, distributed,
hypermedia information systems. It is the data communication protocol used to establish
communication between client and server
HTTP Requests
2) Get request is not secured because data is Post request is secured because data is not
exposed in URL bar. exposed in URL bar.
5) Get request is more efficient and used Post request is less efficient and used less
more than Post. than get.
Servlet Container
• It provides the runtime environment for JavaEE (j2ee) applications. The
client/user can request only a static WebPages from the server. If the
user wants to read the web pages as per input then the servlet container
is used in java.
• The servlet container is the part of web server which can be run in a
separate process.
Servlet API
• The javax.servlet package contains many interfaces and classes that are used by
the servlet or web container. These are not specific to any protocol.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the web
container only once.
public void destroy() is invoked only once and indicates that servlet
is being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
• When the servlet container uses HTTP protocol to send request, then it
creates HttpServletRequest and HttpServletResponse objects.
HttpServletRequest binds the request information like header and
request methods and HttpServletResponse binds all information of HTTP
protocol.
HttpServlet class Methods
• public void service(ServletRequest req,ServletResponse res) dispatches
the request to the protected service method by converting the request
and response object into http type.
• protected void service(HttpServletRequest req, HttpServletResponse
res) receives the request from the service method, and dispatches the
request to the do____() method depending on the incoming http
request type.
• protected void doGet(HttpServletRequest req, HttpServletResponse
res) handles the GET request. It is invoked by the web container.
• protected void doPost(HttpServletRequest req, HttpServletResponse
res) handles the POST request. It is invoked by the web container.
• protected void doHead(HttpServletRequest req, HttpServletResponse
res) handles the HEAD request. It is invoked by the web container.
HttpServletRequest
• HttpServletRequest is an interface and extends the ServletRequest
interface. By extending the ServletRequest this interface is able to allow
request information for HTTP Servlets.
• The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
Life Cycle of a Servlet (Servlet Life Cycle)
• The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
The doGet() Method
• A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
• public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { // Servlet code }
The doPost() Method
• A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
• public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { // Servlet code }
Life Cycle of a Servlet (Servlet Life Cycle)
• There are given 6 steps to create a servlet example. These steps are required for all the servers.
Create and compile servelet code
Add the mapping to web.xml file
Start Apache tomcat
Start web browser and request a server.
The servlet example can be created by three ways:
• By implementing Servlet interface,
• By inheriting GenericServlet class, (or)
• By inheriting HttpServlet class
• The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.
Steps to create a servlet example
Types of Cookie
• Non-persistent cookie
• Persistent cookie
Non-persistent cookie
• It is valid for single session only. It is removed each time when user
closes the browser.
Persistent cookie
• It is valid for multiple session . It is not removed each time when
user closes the browser. It is removed only if user logout or signout.
Cookie class
Constructor Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in
seconds.
public String getName() Returns the name of the cookie. The name
cannot be changed after creation.
For adding cookie or getting the value from the cookie, we need some methods
provided by other interfaces:
• public void addCookie(Cookie ck):method of HttpServletResponse interface is
used to add cookie in response object.
• public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.
Simple example of Servlet Cookies
index.html
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
} }
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
• <web-app> • <servlet-name>s2</servlet-name>
• <servlet> • <servlet-class>SecondServlet</servlet-
• <servlet-name>s1</servlet-name> class>
• <servlet-class>FirstServlet</servlet-class> • </servlet>
• </servlet>
• <servlet-mapping>
• <servlet-mapping> • <servlet-name>s2</servlet-name>
• <servlet-name>s1</servlet-name> • <url-pattern>/servlet2</url-pattern>
• <url-pattern>/servlet1</url-pattern> • </servlet-mapping>
• </servlet-mapping> • </web-app>
• <servlet>
Event and Listener in Servlet
• Event classes and Listener interfaces in the javax.servlet and javax.servlet.http packages
Event interfaces
Event classes The event interfaces are as follows:
The event classes are as follows: ServletRequestListener
ServletRequestEvent ServletRequestAttributeListener
ServletContextEvent ServletContextListener
ServletRequestAttributeEvent ServletContextAttributeListener
ServletContextAttributeEvent HttpSessionListener
HttpSessionEvent HttpSessionAttributeListener
HttpSessionBindingEvent HttpSessionBindingListener
HttpSessionActivationListener
Summary
. Discussed about Java Servlet.
. Discussed about Servlet Life Cycle.
. Discussed about Http request and response.
39
Home Work
Q1. Difference between Generic and http Servlet?
40
References
Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .
41
THANK YOU
For queries
Email: kushagra.e13465@cumail.in
UNIVERSITY INSTITUTE OF ENGINEERING
DEPARTMENT OF AIT - CSE
Bachelor of Engineering (CSE)
Programming in Java (21CSH-244)
By: Kushagra Agrawal (E13465)
2
JAVA SERVER PAGE (JSP)
What is JSP?
• Java Server Pages (JSP) is a technology which is used to develop web
pages by inserting Java code into the HTML pages by making special JSP
tags.
• The JSP tags which allow java code to be included into it are <% ----java
code----%>.
• It is a server side technology.
• It is used for creating web application.
• It is used to create dynamic web content.
• It is an advanced version of Servlet Technology.
• It is a Web based technology helps us to create dynamic and platform
independent web pages.
• In this, Java code can be inserted in HTML/ XML pages or both.
• JSP is first converted into servlet by JSP container before processing the
client’s request.
Servlet Vs JSP
Servlets – JSP –
•Servlet is a Java program which •JSP program is a HTML code which
supports HTML tags too. supports java statements too.To be
•Generally used for developing more precise, JSP embed java in html
business layer(the complex using JSP tags.
computational code) of an enterprise •Used for developing presentation
application. layer of an enterprise application
•Servlets are created and maintained •Frequently used for designing
by Java developers. websites and used by web developers.
JSP syntax
1.Declaration Tag :-It is used to declare variables.
Syntax:- <%! Dec var %>
Example:- <%! int var=10; %>
• The scripting elements provides the ability to insert java code inside the jsp. There
are three types of scripting elements:
• scriptlet tag
• expression tag
• declaration tag
JSP Scriplet tag
• A scriptlet tag is used to execute java source code in JSP.
Syntax is as follows:
• <% java source code %>
Example:
• <html>
• <body>
• <% out.print("welcome to jsp"); %>
• </body>
• </html>
JSP expression tag
• The code placed within JSP expression tag is written to the
output stream of the response. So you need not write
out.print() to write data. It is mainly used to print the values
of variable or method.
• Syntax of JSP expression tag
• <%= statement %>
• Example:
• <html>
• <body>
• <%= "welcome to jsp" %>
• </body>
• </html>
JSP Declaration Tag
• The JSP declaration tag is used to declare fields and methods.
• The code written inside the jsp declaration tag is placed outside
the service() method of auto generated servlet.
• So it doesn't get memory at each request.
• The syntax of the declaration tag is as follows:
• <%! field or method declaration %>
• Example:
• <html>
• <body>
• <%! int data=50; %>
• <%= "Value of the variable is:"+data %>
• </body>
• </html>
Summary
. Discussed about Java Server Pages (JSP).
. Discussed about JSP Architecture.
. Discussed about JSP Life Cycle.
15
Home Work
Q1. What are the life-cycle methods for a JSP?
16
References
Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .
17
THANK YOU
For queries
Email: kushagra.e13465@cumail.in
UNIVERSITY INSTITUTE OF ENGINEERING
DEPARTMENT OF AIT - CSE
Bachelor of Engineering (CSE)
Programming in Java (21CSH-244)
By: Kushagra Agrawal (E13465)
2
Data Base Connectivity in JAVA
Java JDBC
• JDBC stands for Java Database Connectivity.
• JDBC is a Java API to connect and execute the query with the database.
• It is a part of JavaSE (Java Standard Edition).
• JDBC API uses JDBC drivers to connect with the database.
• JDBC Driver is a software component that enables java application to interact with the
database.
• 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 load the driver class.
Ex:
• Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
• The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax of getConnection() method
• 1) public static Connection getConnection(String url)throws SQLException
• 2) public static Connection getConnection(String url,String name,String password) throws SQLException
Ex:
• Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
Ex:
• Statement stmt=con.createStatement();
4) Execute the query
• The executeQuery() method of Statement interface is used to execute queries to
the database.
• This method returns the object of ResultSet that can be used to get all the records
of a table.
Syntax of executeQuery() method:
• public ResultSet executeQuery(String sql)throws SQLException
Ex:
• ResultSet rs=stmt.executeQuery("select * from emp");
• while(rs.next())
• {
• System.out.println(rs.getInt(1)+" "+rs.getString(2));
• }
5) Close the connection object
Create a Table
• Before establishing connection, let's first create a table in oracle database.
• Following is the SQL query to create a table.
• create table emp(id number(10),name varchar2(40),age number(3))
;
Ex:Database Connectivity
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Statement stmt=con.createStatement();
con.close();
2) public boolean previous(): is used to move the cursor to the one row previous from the current position.
3) public boolean first(): is used to move the cursor to the first row in result set object.
4) public boolean last(): is used to move the cursor to the last row in result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified row number in the ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative 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.
8) public int getInt(String columnName): is used to return the data of specified column name of the current row as int.
9) public String getString(int columnIndex): is used to return the data of specified column index of the current row as String.
10) public String getString(String columnName): is used to return the data of specified column name of the current row as String.
Ex:ResultSet
import java.sql.*;
class FetchRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracl
e");
Statement stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_U
PDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp765");
con.close();
}}
PreparedStatement interface
• The PreparedStatement interface is a subinterface of Statement.
• It is used to execute parameterized query.
Example of parameterized query:
• String sql="insert into emp values(?,?,?)";
Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.
public void setString(int paramIndex, String value) sets the String value to the given parameter index.
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.
public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.
public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}catch(Exception e){ System.out.println(e);} } }
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.
Method Description
public int getColumnCount()throws SQLException it returns the total number of columns in the
ResultSet object.
public String getColumnName(int index)throws it returns the column name of the specified column
SQLException index.
public String getColumnTypeName(int index)throws it returns the column type name for the specified
SQLException index.
public String getTableName(int index)throws it returns the table name for the specified column
SQLException index.
Ex:ResultSetMetaData
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
store image in Oracle database
• You can store images in the database in java by the help of PreparedStatement interface.
• The setBinaryStream() method of Prepared Statement is used to set Binary information into the
parameter Index.
Methods:
1) public void setBinaryStream(int paramIndex,InputStream stream) throws SQLException
2) public void setBinaryStream(int paramIndex,InputStream stream, long length) throws SQLException
Ex: Image Store
• For storing image into the database, BLOB (Binary Large Object) data type is used in the table.
For example:
• CREATE TABLE "IMGTABLE" ( "NAME" VARCHAR2(4000), "PHOTO" BLOB )
import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle")
PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
ps.setString(1,“Dog");
FileInputStream fin=new FileInputStream("d:\\g.jpg");
ps.setBinaryStream(2,fin,fin.available());
int i=ps.executeUpdate();
System.out.println(i+" records affected");
con.close();
}catch (Exception e) {e.printStackTrace();} } }
CallableStatement Interface
• CallableStatement interface is used to call the stored procedures and functions.
Syntax:
• public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
Ex:
• CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");
Ex:
To call the stored procedure, you need to create it in the database. Here, we are assuming that
stored procedure looks like this.
create or replace procedure "INSERTR"
(id IN NUMBER,name IN VARCHAR2)
is begin
insert into user values(id,name);
end;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle
");
System.out.println("success");
}
}
Singleton Class
Singleton design pattern in Java
• Singleton Pattern says that just"define a class that has only one instance and
provides a global point of access to it".
• In other words, a class must ensure that only single instance should be created
and single object can be used by all other classes.
• To create the singleton class, we need to have static member of class, private constructor and
static factory method.
• Static member: It gets memory only once because of static, it
contains the instance of the Singleton class.
• Private constructor: It will prevent to instantiate the Singleton class
from outside the class.
• Static factory method: This provides the global point of access to
the Singleton object and returns the instance to the caller.
Ex:1
• class A{
• private static A obj=new A();//Early, instance will be created at load time
• private A(){}
•
• public static A getA(){
• return obj;
• }
•
}
Ex:2
• class A{
• private static A obj;
• private A(){}
• public static A getA(){
• if (obj == null){
• synchronized(Singleton.class){
• if (obj == null){
• obj = new Singleton();//instance will be created at request time
• }
• }
• return obj;
•}
Summary
. Discussed about Database.
. Discussed different types database connectivity with java.
37
Home Work
Q1. What is JDBC Driver?
38
References
Text Book
• Herbert Schildt (2019), “Java The Complete Reference, Ed. 11, McGraw-Hill .
39
THANK YOU
For queries
Email: kushagra.e13465@cumail.in