java imp question
java imp question
Ch-1:JDBC
1. What is JDBC?
Java Database Connectivity (JDBC) is a standard interface for
connecting Java programs to relational databases. It's a
software tool that establishes a connection between a
database and a Java application that uses it. JDBC is
designed to make Java applications database agnostic,
meaning that a program written using JDBC will work with
any JDBC compliant database.
2. What is types of JDBC driver?
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
1. Declarative Statements
2. Assignment Statements
3. Input/Output Statements
4. Control Statements
5. Looping Statements
6. Jump Statements
7. What is use of executeQuery(), executeUpdate() and execute().
execute()
Executes any SQL statement in a Prepared Statement
object. It returns a Boolean value that indicates whether a
ResultSet object can be retrieved.
executeQuery()
Executes an SQL query in a Prepared Statement object
and returns the ResultSet object generated by the
query. It returns a ResultSet that contains the data
returned by the query.
executeUpdate()
Executes an SQL INSERT, UPDATE, or DELETE statement
in a Prepared Statement object. It returns an integer
value representing the number of rows affected by the
SQL command it executes.
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.
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 java.sql package contains interfaces and
classes of JDBC API.
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 sun.jdbc.odbc package which includes a native library to
access ODBC characteristics.
11. Write JDBC program that inserts record in employee table field emp-no,
name and salary.
import java.sql.*;
// Create a statement
Statement stmt = conn.createStatement();
12. Write JDBC program to delete a record from student table who belong to
pune city.
import java.sql.*;
// Create a statement
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (SQLException e) {
System.out.println(e.getMessage());
return;
}
Ch2-Multithreading
1. What is thread? How to set priority of thread?
The setPriority() method of thread class is used to change
the thread's priority. Every thread has a priority which is
represented by the integer number between 1 to 10. Thread
class provides 3 constant properties: public static int
MIN_PRIORITY: It is the maximum priority of a thread.
2. Which are method are used in Interthread Communication?
In Java, inter-thread communication is achieved using
the wait(), notify(), and notifyAll() methods of the Object
class. These methods are available in the object class but not in
the thread class. All these methods must be used within a
synchronized block only.
import java.util.Scanner;
// t1 finishes before t2
t1.join();
t2.join();
}
// Sleep
Thread.sleep(2000);
}
}
}
}
5. Differentiate between sleep() and interrupt() method
In Java, the sleep() method pauses a thread's execution for a
set amount of time. The interrupt() method allows for
interruptions.
Here are some differences between the sleep() and
interrupt() methods:
When to use
The sleep() method is used when a thread needs to wait for
an external event or to introduce a delay in execution. The
interrupt() method is used when a thread needs to stop or
interrupt another thread.
Effect on thread
During sleep, the thread does not release the lock. If the
thread is interrupted while it is sleeping, it throws an
InterruptedException.
Effect on interrupt flag
Calling interrupt() on a sleeping/waiting thread will stop it
sleeping/waiting but it will not know that it was interrupted.
class Counter {
int count = 0;
public synchronized void increment() {
count++;
}
}
public BouncingBall() {
x = 100;
y = 100;
dx = 5;
dy = 5;
thread = new BallThread(this);
thread.start();
}
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void init() {
executorService = Executors.newFixedThreadPool(4);
}
@Override
public void paint(Graphics g) {
executorService.submit(() -> drawTemple(g));
}
g.setColor(Color.WHITE);
g.drawRect(100, 100, 200, 300);
g.fillRect(100, 100, 200, 300);
g.setColor(Color.RED);
g.fillRect(120, 120, 160, 260);
g.setColor(Color.BLACK);
g.drawRect(120, 120, 160, 260);
g.setColor(Color.WHITE);
g.fillRect(130, 130, 140, 240);
g.setColor(Color.BLACK);
g.drawRect(130, 130, 140, 240);
g.setColor(Color.RED);
g.fillRect(140, 140, 120, 220);
g.setColor(Color.BLACK);
g.drawRect(140, 140, 120, 220);
g.setColor(Color.WHITE);
g.fillRect(150, 150, 100, 200);
g.setColor(Color.BLACK);
g.drawRect(150, 150, 100, 200);
g.setColor(Color.RED);
g.fillRect(160, 160, 80, 180);
g.setColor(Color.BLACK);
g.drawRect(160, 160, 80, 180);
g.setColor(Color.WHITE);
g.fillRect(170, 170, 60, 160);
g.setColor(Color.BLACK);
g.drawRect(170, 170, 60, 160);
g.setColor(Color.RED);
g.fillRect(180, 180, 40, 140);
g.setColor(Color.BLACK);
g.drawRect(180, 180, 40, 140);
g.setColor(Color.WHITE);
g.fillRect(190, 190, 20, 120);
g.setColor(Color.BLACK);
g.drawRect(190, 190, 20, 120);
}
@Override
public void destroy() {
executorService.shutdown();
}
}
Ch-3:Networking
Connection-oriented No Yes
String receivedMessage;
while (true) {
receivedMessage = cread.readLine();
System.out.println(receivedMessage);
// sending to client
String sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
pwrite.flush();
}
}
}
JSP
4) Cookies:
Cookies are the mostly used technology for session tracking. Cookie is a key
value pair of
information, sent by the server to the browser. This should be saved by the
browser in its
space in the client computer.
5) Session Tracking API:
Session tracking API is built on top of the first four methods. This is inorder to
help the
developer to minimize the overhead of session tracking. This type of session
tracking is
provided by the underlying technology.
mport java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Create a statement
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
out.println("Error creating statement");
return;
}
Directives are elements of a JSP source code that guide the web
container on how to translate the JSP page into its respective
servlet. There are three different JSP directives available:
Page directive: Defines attributes that apply to an entire
JSP page
Include directive
Taglib directive
2.Write JSP program to check whether given email_id is valid or not should
contain one ‘@’ symbol.
<%@ page import="java.util.regex.Matcher" %>
<%@ page import="java.util.regex.Pattern" %>
<%
String email = request.getParameter("email");
if (matcher.find()) {
// The email address is valid.
out.println("The email address is valid.");
} else {
// The email address is invalid.
out.println("The email address is invalid.");
}
%>
3.Explain different scriplet in java.
There are three types of scriptlets in JSP:
1. Expression Scriptlet: Expression scriptlets are used to
perform simple calculations or operations. They are enclosed in
the <%= %> tags. For example, the following expression
scriptlet prints the value of the variable "name" to the console:
Code
<% out.println(name); %>
2. Declaration Scriptlet: Declaration scriptlets are used to
declare variables and methods. They are enclosed in the <
%! %> tags. For example, the following declaration scriptlet
declares a variable called "name" and a method called
"greet()":
Code
<%!
String name;
public void greet() {
out.println("Hello, " + name);
}
%>
</body>
<form method="post">
<table border="2">
<tr>
<td>ROLL NUMBER</td>
<td>NAME</td>
<td>EMAIL</td>
<td>MARKS</td>
</tr>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
String username="root";
String password="root";
String query="select * from jsp1";
Connection
conn=DriverManager.getConnection(url,username,passwor
d);
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
%>
<tr>
<td><%=rs.getInt("ROLL NUMBER ") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getString("EMAIL") %></td>
<td><%=rs.getString("MARKS") %></td>
</tr>
<%
}
%>
</table>
<%
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</form>
</html>
1.Define hibernate .
Hibernate ORM (or simply Hibernate) is an object–relational mapping
tool for the Java programming language. It provides a framework for
mapping an object-oriented domain model to a relational database.
2.Define criteria .
The Criteria API is used to define queries for entities and their persistent
state by creating query-defining objects. Criteria queries are written
using Java programming language APIs, are typesafe, and are portable.
Such queries work regardless of the underlying data store.
3.Persistent classes .
Persistent classes are classes in an application that implement the
entities of the business problem (e.g. Customer and Order in an E-
commerce application). Not all instances of a persistent class are
considered to be in the persistent state. For example, an instance can
instead be transient or detached.
4.Session
Session in Java is a stateful communication between a client
and a server. It is a way to track the user's interaction with the
application across multiple requests. Sessions are typically
used to store user-specific information, such as the user's
name, shopping cart contents, or login status.
Answer the following question
5.What is hibernate ? Explain Hibernate architecture ?
Hibernate: Hibernate is a framework which is used to develop
persistence logic which is independent of Database software.
In JDBC to develop persistence logic we deal with primitive
types
SessionFactory:
SessionFactory is an Interface which is present in
org.hibernate package and it is used to create Session
Object.
It is immutable and thread-safe in nature.
buildSessionFactory() method gathers the meta-data
which is in the cfg Object.
From cfg object it takes the JDBC information and
create a JDBC Connection.
SessionFactory factory=cfg.buildSessionFactory();
Session:
Session is an interface which is present in
org.hibernate package. Session object is created based
upon SessionFactory object i.e. factory.
It opens the Connection/Session with Database
software through Hibernate Framework.
It is a light-weight object and it is not thread-safe.
Session object is used to perform CRUD operations.
Session session=factory.buildSession();
Transaction :
The transaction object specifies the atomic unit of work .
The org.hibernate . Transaction interface provides methods for
transaction management
Connection provider
It is a factory of JDBC connection .
It abstract the application from Driver Manager or Data Source .
Its optional
Transfactory :
It is a factory of transaction its optional
6.What is the difference between get and load method ?
Hibernate provides different methods to fetch data from the
database.
1. get() method
get() method is used to retrieve a persistent object
from the database. It is a member of the Session
interface, and it takes the class of the object to be
retrieved and the primary key of the object as
arguments.
get() method only hits the database if the object is not
present in the session cache. If the same object is
already present in the cache then it returns previously
stored data from the cache.
get() method returns null if there is no object present
in the database.
2. load() method
load() method is used to retrieve an object from the
database by its identifier (primary key). It is used to
initialize a proxy object instead of a fully-initialized
object, so it can be used to lazily load the object when
it is needed.
load() method does not retrieve the object from the
database when it is called. Instead, it returns a proxy
object that represents the object. The actual object is
only retrieved from the database when it is needed,
such as when a method of the object is called or a
property is accessed. This technique is known as “lazy
loading” and it is used to improve the performance of
Hibernate by avoiding unnecessary database queries.
load() method throws ObjectNotFoundException if
there is no object found in the database.
12.What is ORM ?
ORM stands for Object Relational Mapping, and it's a software
design pattern and programming technique that translates
between the data representations used by databases and those
used in object-oriented programming. ORM allows developers
to interact with objects in their code while seamlessly persisting
and retrieving data from a database.