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

java imp question

The document covers important questions related to JDBC and Multithreading in Java. It explains JDBC concepts such as drivers, PreparedStatement, CallableStatement, and provides examples of JDBC programs for inserting and deleting records. Additionally, it discusses thread management, inter-thread communication, thread life cycle, synchronization, and the differences between sleep() and interrupt() methods.

Uploaded by

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

java imp question

The document covers important questions related to JDBC and Multithreading in Java. It explains JDBC concepts such as drivers, PreparedStatement, CallableStatement, and provides examples of JDBC programs for inserting and deleting records. Additionally, it discusses thread management, inter-thread communication, thread life cycle, synchronization, and the differences between sleep() and interrupt() methods.

Uploaded by

abhinavkale24
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Advanced Java Important Questions

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

3. What is used of PreparedStatement interface?


The PreparedStatement interface is a subinterface of the
Statement. It is used to execute parameterized queries.
4. What is used of CallableStatement interface?
The CallableStatement interface is used to execute SQL
stored procedures. It extends
the PreparedStatement interface and supports input
parameters, output parameters, or input and output
parameters, or no parameters.

5. Differentiate between Statement and PreparedStatement interface.


5. What is used of Statement interface?
The statement interface is used to create SQL basic statements in
Java it provides methods to execute queries with the database.
6. What is statement?what is its different types?

Statement are instructions which tell the computer what to do.


Statements are composed of valid tokens and keywords of the
computer language in which they are coded. The different
types of statements used in Java are:

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.

8. Explain different drivers in JDBC.


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
 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.

9. Explain JDBC Architecture in detail.


1. Application: It is a java applet or a servlet that
communicates with a data source.
2. The JDBC API: The JDBC API allows Java programs to
execute SQL statements and retrieve results. Some of
the important classes and interfaces defined in JDBC
API are as follows:
3. DriverManager: It plays an important role in the JDBC
architecture. It uses some database-specific drivers to
effectively connect enterprise applications to
databases.
4. JDBC drivers: To communicate with a data source
through JDBC, you need a JDBC driver that intelligently
communicates with the respective data source

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.*;

public class InsertEmployee {

public static void main(String[] args) {

// Create a connection to the database


Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/myd
b", "root", "password");

// Create a statement
Statement stmt = conn.createStatement();

// Prepare the SQL query


String sql = "INSERT INTO employee (empno, name,
salary) VALUES (?, ?, ?)";

// Set the values for the query parameters


stmt.setInt(1, 1001);
stmt.setString(2, "John Doe");
stmt.setDouble(3, 10000.00);
// Execute the query
stmt.executeUpdate(sql);

// Close the statement and connection


stmt.close();
conn.close();

System.out.println("Employee record inserted


successfully!");
}
}

12. Write JDBC program to delete a record from student table who belong to
pune city.

import java.sql.*;

public class DeleteRecord {

public static void main(String[] args) {


// Create a connection to the database
Connection conn = null;
try {
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/stud
ent_db", "root", "password");
} catch (SQLException e) {
System.out.println(e.getMessage());
return;
}

// Create a statement
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (SQLException e) {
System.out.println(e.getMessage());
return;
}

// Create a SQL query to delete the record


String sql = "DELETE FROM student WHERE city = 'Pune'";

// Execute the query


try {
stmt.executeUpdate(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
return;
}

// Close the statement and connection


try {
stmt.close();
conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
return;
}

// Print a success message


System.out.println("Record deleted successfully!");
}
}

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.

3. Explain Thread life cycle with suitable diagram


1. New Thread: When a new thread is created, it is in
the new state. The thread has not yet started to run
when the thread is in this state. When a thread lies in
the new state, its code is yet to be run and hasn’t
started to execute.
2. Runnable State: A thread that is ready to run is
moved to a runnable state. In this state, a thread
might actually be running or it might be ready to run at
any instant of time. It is the responsibility of the thread
scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of
time to each individual thread. Each and every thread
runs for a short while and then pauses and relinquishes
the CPU to another thread so that other threads can
get a chance to run. When this happens, all such
threads that are ready to run, waiting for the CPU and
the currently running thread lie in a runnable state.
3. Blocked: The thread will be in blocked state when it is
trying to acquire a lock but currently the lock is
acquired by the other thread. The thread will move
from the blocked state to runnable state when it
acquires the lock.
4. Waiting state: The thread will be in waiting state
when it calls wait() method or join() method. It will
move to the runnable state when other thread will
notify or that thread will be terminated.
5. Timed Waiting: A thread lies in a timed waiting state
when it calls a method with a time-out parameter. A
thread lies in this state until the timeout is completed
or until a notification is received. For example, when a
thread calls sleep or a conditional wait, it is moved to a
timed waiting state.
6. Terminated State: A thread terminates because of
either of the following reasons:

 Because it exits normally. This happens when


the code of the thread has been entirely
executed by the program.
 Because there occurred some unusual
erroneous event, like a segmentation fault or
an unhandled exception.

4. Explain interthread communication with example.


Inter-thread communication in Java is a mechanism in which a
thread is paused running in its critical section and another
thread is allowed to enter (or lock) in the same critical section
to be executed.

To avoid polling, Java uses three methods, namely, wait(),


notify(), and notifyAll(). All these methods belong to object
class as final so that all classes have them. They must be used
within a synchronized block only.
 wait(): It tells the calling thread to give up the lock
and go to sleep until some other thread enters the
same monitor and calls notify().
 notify(): It wakes up one single thread called wait() on
the same object. It should be noted that calling notify()
does not give up a lock on a resource.
 notifyAll(): It wakes up all the threads called wait() on
the same object.

import java.util.Scanner;

public class threadexample


{
public static void main(String[] args) throws
InterruptedException
{
final PC pc = new PC();
// Create a thread object that calls pc.produce()
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Create another thread object that calls


// pc.consume()
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Start both threads


t1.start();
t2.start();

// t1 finishes before t2
t1.join();
t2.join();
}

// PC (Produce Consumer) class with produce() and


// consume() methods.
public static class PC
{
// Prints a string and waits for consume()
public void produce()throws InterruptedException
{
// synchronized block ensures only one thread
// running at a time.
synchronized(this)
{
System.out.println("producer thread
running");

// releases the lock on shared resource


wait();

// and waits till some other method invokes


notify().
System.out.println("Resumed");
}
}

// Sleeps for some time and waits for a key press.


After key
// is pressed, it notifies produce().
public void consume()throws InterruptedException
{
// this makes the produce thread to run first.
Thread.sleep(1000);
Scanner s = new Scanner(System.in);

// synchronized block ensures only one thread


// running at a time.
synchronized(this)
{
System.out.println("Waiting for return
key.");
s.nextLine();
System.out.println("Return key pressed");

// notifies the produce thread that it


// can wake up.
notify();

// 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.

7. Explain thread synchronization with suitable example.

Synchronization in Java is the process of controlling access to


shared resources by multiple threads. It ensures that only one
thread can access a shared resource at a time, preventing data
corruption and inconsistencies. This is achieved by using the
synchronized keyword.
There are two ways to synchronize threads in Java:
 Using synchronized methods:
When a method is synchronized, only one thread can
execute it at a time. All other threads that try to execute the
method will be blocked until the first thread finishes
executing it.
 Using synchronized blocks:
A synchronized block is a block of code that is surrounded by
the synchronized keyword. Only one thread can execute a
synchronized block at a time. All other threads that try to
execute the block will be blocked until the first thread
finishes executing it.
Synchronization is important in Java because it helps to prevent
data corruption and inconsistencies. When multiple threads are
accessing the same shared resource, it is possible for them to
interfere with each other and cause data
corruption. Synchronization prevents this from happening by
ensuring that only one thread can access the shared resource
at a time.

class Counter {
int count = 0;
public synchronized void increment() {
count++;
}
}

public class Main {


public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(counter.count); // 20000
}
}
7. Which are different ways to create thread?

There are 2 ways to create threads in Java:


1. 1. Extending the Thread class:
This is the simplest way to create a thread. You just need to
create a new class that extends the Thread class and
override the run() method. The run() method is where you
will put the code that you want to run in the thread.
2. 2. Implementing the Runnable interface:
This is a more flexible way to create a thread. You can
create a class that implements the Runnable interface and
pass an instance of that class to the Thread constructor. The
Thread constructor will then create a new thread and call
the run() method on the Runnable object.
Here is an example of how to create a thread by extending the
Thread class:
Java
public class MyThread extends Thread {
public void run() {
// This code will run in the thread
}
}

public class Main {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
Here is an example of how to create a thread by implementing
the Runnable interface:
Java
public class MyRunnable implements Runnable {
public void run() {
// This code will run in the thread
}
}

public class Main {


public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}

8. Write multithreading program in java to display all vowels from given


string.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VowelDisplay {

public static void main(String[] args) {


String str = "Hello World!";

// Create a thread pool with 4 threads


ExecutorService executorService = Executors.newFixedThreadPool(4);

// Create a runnable task to display the vowels from a given string


Runnable task = () -> {
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
System.out.println(ch);
}
}
};

// Submit the task to the thread pool


executorService.submit(task);

// Shut down the thread pool


executorService.shutdown();
}
}
9. Write a java program to display name and priority of given thread.Change
name of thread to mythread and priority to 2. Display details of thread.
public class DisplayThreadDetails {

public static void main(String[] args) {


Thread thread = Thread.currentThread();
String threadName = thread.getName();
int threadPriority = thread.getPriority();

System.out.println("Current thread name: " + threadName);


System.out.println("Current thread priority: " + threadPriority);

// Change thread name to "thread" and priority to 2


thread.setName("thread");
thread.setPriority(2);

System.out.println("New thread name: " + thread.getName());


System.out.println("New thread priority: " + thread.getPriority());
}
}
10. Write a multithreading program for bouncing ball effect(Use Runnable
interface).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BouncingBall extends JPanel implements Runnable


{

private int x, y, dx, dy;


private BallThread thread;

public BouncingBall() {
x = 100;
y = 100;
dx = 5;
dy = 5;
thread = new BallThread(this);
thread.start();
}

public void run() {


while (true) {
x += dx;
y += dy;

if (x < 0 || x > getWidth()) {


dx = -dx;
}

if (y < 0 || y > getHeight()) {


dy = -dy;
}

repaint();

try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void paintComponent(Graphics g) {


super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(x, y, 10, 10);
}

public static void main(String[] args) {


JFrame frame = new JFrame("Bouncing Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new BouncingBall());
frame.setVisible(true);
}
}

class BallThread extends Thread {

private BouncingBall ball;

public BallThread(BouncingBall ball) {


this.ball = ball;
}

public void run() {


ball.run();
}
}
11. Write multithreading program to display drawing temple on the applet
container.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TempleApplet extends Applet {

private ExecutorService executorService;

@Override
public void init() {
executorService = Executors.newFixedThreadPool(4);
}

@Override
public void paint(Graphics g) {
executorService.submit(() -> drawTemple(g));
}

private void drawTemple(Graphics g) {


g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());

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

1. Define the term socket.


Ans: A socket represents the end-point of the network communication link
between two processes. It allows communication between two different
processes on the same or different machines.
2. Difference between Datagram socket and stream socket?
Datagram sockets are connectionless, meaning that they do
not establish a connection with the remote host before sending
data. This makes them ideal for applications that need to send
small amounts of data quickly, such as online gaming and video
streaming.
Stream sockets, on the other hand, are connection-oriented,
meaning that they establish a connection with the remote host
before sending data. This makes them ideal for applications
that need to send large amounts of data reliably, such as file
transfers and email.
Here is a table that summarizes the key differences between
datagram sockets and stream sockets in Java:
Feature Datagram Socket Stream Socket

Connection-oriented No Yes

Data transfer Unreliable Reliable

Order of data Unordered Ordered

Speed Fast Slow

Ideal for Small amounts of data Large amounts of data

3. State any two methods of Socket class.

Here are two methods of Socket class:


1. accept()
This method listens for a connection to be made to this socket
and accepts it.
2. bind()
This method binds the ServerSocket to a specific address (IP
address and port number).

4. List any two well known port numbers.


Port numbers 80 and 443 are two well-known port
numbers. Port 80 is the default port that HyperText Transfer
Protocol (HTTP) Web servers listen on for web browser
requests. Port 443 is the default for secure HTTP.

5. What is stub and skeleton?Explain


Stub − A stub is a representation (proxy) of the remote object at client. It
resides in the client system; it acts as a gateway for the client program.
Skeleton − This is the object which resides on the server side. stub
communicates with this skeleton to pass request to the remote object.

6. Write note on InetAddress class and explain its methods.


The InetAddress class has the following methods:
 equals(): Returns true if the IP address is the same as the
object specified.
 getAddress(): Returns the raw IP address of the
InetAddress object as an array.
 getByAddress(): Creates an InetAddress object.
 getCanonicalHostName(): Returns the canonical hostname
of the IP address.
 getHostAddress(): Returns the IP address as a string.
 getHostName(): Returns the hostname of the IP address.
 isAnyLocalAddress(): Returns true if the IP address is an
any-local address.
 isLinkLocalAddress(): Returns true if the IP address is a
link-local address.
 isLoopbackAddress(): Returns true if the IP address is a
loopback address.
 isMulticastAddress(): Returns true if the IP address is a
multicast address.
 isSiteLocalAddress(): Returns true if the IP address is a
site-local address.
 resolveAddress(): Resolves the hostname to an IP address.
 toString(): Returns the IP address as a string.
The InetAddress class is used to encapsulate both, the
numerical IP address and the domain name for that
address. The InetAddress class has the inability to create
objects directly, hence factory methods are used for the
purpose. This method creates and returns an InetAddress
based on the provided hostname and IP address.
The InetAddress class is a useful tool for working with IP
addresses in Java. It provides a number of methods that can be
used to resolve hostnames to IP addresses, and vice versa. It
also provides methods for getting the canonical hostname of an
IP address, and for determining whether an IP address is a
loopback address, a multicast address, or a site-local address.

7. Which class is used to convert between hostname and Internet Address?


You can use the InetAddress class's getByName() method to convert a
hostname to an IP address. For instance: String hostName =
"www.example.com"; InetAddress address = InetAddress.
getByName(hostName);
8.What is accept() in networking?
The accept() function is a system call in Unix-like operating
systems that is used by a server to accept a connection request
from a client. It takes a socket descriptor as an argument and
returns a new socket descriptor for the accepted
connection. The new socket descriptor can then be used to
communicate with the client.
The accept() function blocks the server until a connection
request arrives. If there are connection requests in the backlog
queue, a connection is established with the first client in the
queue. If there are no connection requests in the backlog
queue, the server blocks until a connection request arrives.
The accept() function returns a new socket descriptor that can
be used to communicate with the client. The new socket
descriptor has the same properties as the socket descriptor
that was passed to the accept() function.

9.What is getLocalHost() method


The getLocalHost() method in Java is used to return an
InetAddress object that represents the local host. The local host
is the computer on which the Java program is running. The
getLocalHost() method is a static method of the InetAddress
class.
The syntax of the getLocalHost() method is:
Java
public static InetAddress getLocalHost() throws
UnknownHostException

8. Write socket program for chatting application.


import java.io.*;
import java.net.*;

public class ChatServer {


public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(3000);
System.out.println("Server ready for chatting");
Socket socket = serverSocket.accept();
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new
InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = socket.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);

// reading from client (cread object)


InputStream istream = socket.getInputStream();
BufferedReader cread = new BufferedReader(new
InputStreamReader(istream));

String receivedMessage;

while (true) {
receivedMessage = cread.readLine();
System.out.println(receivedMessage);

// sending to client
String sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
pwrite.flush();
}
}
}

9.Write a socket program to accept file name from user,Check whether it is


available on server or not.if it is available display content on client machine
otherwise display an error
message.
10.Explain steps for creating a TCP connection between two computer using
socket.
1. Server creates socket and listens.: The server creates a
socket and listens for incoming connections on a specific
port.
2. Client creates socket and connects.: The client creates a
socket and connects to the server's socket on the
specified port.
3. Transport layer delivers message to server.: The transport
layer delivers the message from the client to the server.
4. Server creates socket & process.: The server creates a
new socket and process to handle the connection from the
client.
5. Transport layer delivers message to client.: The transport
layer delivers the message from the server to the client.
6. Sockets closed.: When the client and server are finished
communicating, they close their sockets.
11.Write socket based client and server program to accept a number from
client,read this number at server and if this number is prime, then revert it to
client.
import java.io.*;
import java.net.*;

public class FileTransferClient {

public static void main(String[] args) throws Exception {

// Get the file name from the user.


System.out.println("Enter the file name: ");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String fileName = br.readLine();

// Create a socket to the server.


Socket socket = new Socket("localhost", 5000);

// Create an output stream to the server.


DataOutputStream dos = new
DataOutputStream(socket.getOutputStream());

// Send the file name to the server.


dos.writeUTF(fileName);

// Create an input stream from the server.


DataInputStream dis = new
DataInputStream(socket.getInputStream());

// Read the response from the server.


String response = dis.readUTF();

// Check if the file is available on the server.


if (response.equals("File not found")) {
System.out.println("File not found on server.");
} else {

// Create a file on the client machine.


File file = new File(fileName);

// Create an output stream to the file.


FileOutputStream fos = new FileOutputStream(file);

// Read the file content from the server and write it to


the file on the client machine.
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = dis.read(buffer)) > 0) {
fos.write(buffer, 0, bytesRead);
}

// Close the output stream to the file.


fos.close();

// Display the file content on the client machine.


System.out.println("File content: ");
BufferedReader br1 = new BufferedReader(new
FileReader(file));
String line;
while ((line = br1.readLine()) != null) {
System.out.println(line);
}

// Close the input stream from the server.


dis.close();
}

// Close the socket.


socket.close();
}
}

JSP

1.What are directives in JSP?How are they represented?


2.Write JSP program to check whether given email_id is valid or not should
contain one ‘@’
symbol.
3.Explain different scriplet in java.
3.Write jsp program to validate user name,where username should not be
left blank and it
should contain characters only.
4.Write a jsp program to accept student roll number and if this rollno exists in
database then
delete it from student table.

Ch-4:Servlet and JSP

1.What is servlet?Which are types of servlet?


Servlet is a server side java program that services HTTP requests and returns
result as HTTP
response.
Types of servlet:
1.GenericServlet:
i)It extends javax.servlet.GenericServlet
ii)GenericServlets are protocol independent.
iii)They contain no inherent HTTP protocol support
2.HttpServlet
i) It extends javax.servlet.HttpServlet
ii)HttpServlet have built in protocol support.
iii)Implement constructor method init() and the destructor method destroy().

2.What is servlet config object?


: ServletConfig object is created by the web container for each servlet. This
object can be used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we
don&#39;t need to change
the servlet. So it is easier to manage the web application if any specific content
is modified
from time to time.

3.What is use of cookie?


A cookie is a small piece of information that is persisted between the multiple
client
requests.
A cookie has a name, a single value, and optional attributes such as a
comment, path and
domain qualifiers, a maximum age, and a version number.

4.Which are types of cookies?


1.Non-persistent cookie:It is valid for single session only. It is removed each
time when user closes the browser.
2.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.
5.Which method is used to send a cookie to the client from servlet?
Ans: addCookie() is used to add specified cookie to a response.
6.What is session?
Ans: Session simply means a particular interval of time. A session is a
conversation between
the server and a client. A conversation consists series of continuous request
and response.
7.What is session tracking?How is it implemented in servlet?
Ans: Session Tracking is a way to maintain state (data) of an user. It is also
known as session management in servlet.
Session Tracking Methods:
1) User Authorization:
Users can be authorized to use the web application in different ways. Basic
concept is that the
user will provide username and password to login to the application. Based on
that the user
can be identified and the session can be maintained.
2) Hidden Fields:
&lt;INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”&gt;
Hidden fields like the above can be inserted in the webpages and information
can be sent to
the server for session tracking.
3) URL Rewriting:
Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url.

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.

8. Http is stateless protocol.Justify.


Ans: Http protocol is a stateless so we need to maintain state using session
tracking
techniques. Each time user requests to the server, server treats the request as
the new request.
So we need to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request.
9.What are advantages of servlet?
Ans:
1. Platform Independence
Servlets are written entirely in java so these are platform independent. Servlets
can run
on any Servlet enabled web server. For example if you develop an web
application in
windows machine running Java web server, you can easily run the same on
apache web
server (if Apache Serve is installed) without modification or compilation of
code.
Platform independency of servlets provide a great advantages over alternatives
of
servlets.
2. Performance
Due to interpreted nature of java, programs written in java are slow. But the
java
servlets runs very fast. These are due to the way servlets run on web server. For
any
program initialization takes significant amount of time. But in case of servlets
initialization takes place first time it receives a request and remains in memory
till times
out or server shut downs. After servlet is loaded, to handle a new request it
simply
creates a new thread and runs service method of servlet. In comparison to
traditional
CGI scripts which creates a new process to serve the request.
3. Extensibility
Java Servlets are developed in java which is robust, well-designed and object
oriented
language which can be extended or polymorphed into new objects. So the java
servlets
take all these advantages and can be extended from existing class to provide
the ideal
solutions.
4. Safety Java provides very good safety features like memory management,
exception handling
etc. Servlets inherits all these features and emerged as a very powerful web
server
extension.
5. Secure
Servlets are server side components, so it inherits the security provided by the
web
server. Servlets are also benefited with Java Security Manager.

10.What is difference between doGet() and doPost().


The main difference between doGet() and doPost() is the HTTP
method they handle. doGet() handles HTTP GET requests, while
doPost() handles HTTP POST requests.
HTTP GET requests are used to request data from a
server. HTTP POST requests are used to send data to a server.
doGet() is typically used for retrieving data from a server, such
as when a user clicks on a link. doPost() is typically used for
sending data to a server, such as when a user submits a form.
Here is a table that summarizes the key differences between
doGet() and doPost():
Feature doGet() doPost()

HTTP method GET POST

Typical use Retrieving data from a server Sending data to a server

Security Less secure More secure

Performance Faster Slower

11.Write servlet program to display Hit count.


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HitCounter extends HttpServlet {


private int hitCount;
public void init() {
// Initialize the hit count.
hitCount = 0;
}

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Set the response content type.
response.setContentType("text/html");

// This method executes whenever the servlet is hit.


// Increment the hit count.
hitCount++;

// Get the PrintWriter object to write the hit count to the


response.
PrintWriter out = response.getWriter();

// Write the hit count to the response.


out.println("<html><head><title>Hit
Counter</title></head>");
out.println("<body>");
out.println("<h1>Hit Count: " + hitCount + "</h1>");
out.println("</body></html>");

// Close the PrintWriter object.


out.close();
}

public void destroy() {


// Do nothing.
}
}
12.Write servlet program to accept name of city from where employee
belongs and display
all records from employee table who belongs to that city in tabular format.

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;

public class EmployeeServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Get the city name from the request


String city = request.getParameter("city");

// Connect to the database


Connection conn = null;
try {
conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/myd
b", "root", "password");
} catch (SQLException e) {
e.printStackTrace();
out.println("Error connecting to database");
return;
}

// Create a statement
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
out.println("Error creating statement");
return;
}

// Execute the query


ResultSet rs = null;
try {
rs = stmt.executeQuery("SELECT * FROM employee
WHERE city = '" + city + "'");
} catch (SQLException e) {
e.printStackTrace();
out.println("Error executing query");
return;
}

// Display the results in a table


out.println("<table border='1'>");
out.println("<tr><th>Employee
ID</th><th>Name</th><th>City</th></tr>");
while (rs.next()) {
out.println("<tr><td>" + rs.getInt("id") + "</td><td>"
+ rs.getString("name") + "</td><td>" + rs.getString("city") +
"</td></tr>");
}
out.println("</table>");

// Close the connection


try {
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
out.println("Error closing connection");
}
}
}
JSP

1.What are directives in JSP?How are they represented?

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

Directives are represented as XML elements when they appear


in a JSP document. The syntax for a JSP directive is <%@
directive attribute=``value'' %>

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");

// Check if the email address contains one '@' symbol.


Pattern pattern = Pattern.compile("^[A-Za-z0-9+_.-]+@(.+)$");
Matcher matcher = pattern.matcher(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);
}
%>

3. Scriptlet: Scriptlets are used to embed Java code in a JSP


page. They are enclosed in the <% %> tags. For example, the
following scriptlet prints the value of the variable "name" to the
console and then calls the "greet()" method:
Code
<%
out.println(name);
greet();
%>
Scriptlets can be used to perform a variety of tasks, such as:
Accessing and modifying database data, Sending and receiving
email, Generating dynamic content, and Interacting with other
web applications.

4.Write jsp program to validate user name,where username should not be


left blank and it should contain characters only.
<%
String username = request.getParameter("username");

if (username == null || username.equals("")) {


out.println("Username cannot be blank.");
} else if (!username.matches("[a-zA-Z0-9]+")) {
out.println("Username must contain only characters.");
} else {
out.println("Username is valid.");
}
%>
5.Write a jsp program to accept student roll number and if this rollno exists in
database then delete it from student table.

</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>

CH 6: SPRING AND HIBERNATE

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.

7.What is the difference between update and merge method ?


Feature update merge(
() )

Can update objects that are not in the No Yes


session

Can update detached objects No Yes

Handles concurrent updates safely No Yes


The update() method can only be used to update objects that
are already in the session. If the object is not in the session, the
update() method will throw an exception.
The merge() method can be used to update objects that are
already in the session or objects that are not in the session. If
the object is not in the session, the merge() method will load
the object from the database and then update it.

8.What are the states of object in hibernate ?

There are four states of an object in Hibernate:


1. Transient
: An object that is not associated with any Hibernate
Session. It does not exist in the database and will not be
saved automatically.
2. Persistent
: An object that is associated with a Hibernate Session. It
represents a row in the database.
3. Detached
: An object that is no longer associated with any Hibernate
Session. This can happen when the Session is closed.
4. Removed
: An object that has been deleted from the database.

9.What are the inheritance mapping strategies ?

There are three inheritance mapping strategies defined in the


hibernate:

1. Table Per Hierarchy

This strategy maps all the classes in an inheritance


hierarchy to a single table. A discriminator column is used
to distinguish between the different classes.

2. Table Per Concrete class


This strategy maps each concrete class in an inheritance
hierarchy to its own table. The parent class is not mapped
to a table.

3. Table Per Subclass

This strategy maps each class in an inheritance hierarchy


to its own table. A join table is used to link the tables
together.

Answer the following question in short


10.What is the difference between session.save() and session.persist()
method?
The main difference between the save() and persist() methods
in Hibernate is that save() returns the generated identifier,
while persist() does not.
Additionally, save() will save the object to the database
immediately, while persist() will only mark the object as
persistent and save it to the database when the transaction is
committed.
Finally, save() can be used inside or outside of a transaction,
while persist() can only be used inside of a transaction.
Here is a table that summarizes the key differences between
the two methods:
Feature save( persist(
) )

Returns generated identifier Yes No

Saves object to database immediately Yes No

Can be used inside or outside of a transaction Yes No


In general, you should use the save() method if you need to
know the generated identifier immediately after saving the
object. You should use the persist() method if you want to
ensure that the object is saved to the database when the
transaction is committed.

11.What are the core interfaces of hibernate ?


The core interfaces of Hibernate framework are:
 Configuration.
 SessionFactory.
 Session.
 Query.
 Criteria.
 Transaction.

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.

13. Mention some of the advantages of using ORM over JDBC.


 Fast application development: ORM allows business code
to access objects, rather than database tables, which can
speed up development
 Automatic key generation: ORM generates keys
automatically
 Transaction management: ORM manages transactions
 Hides SQL queries: ORM hides SQL queries from object-
oriented logic
 Database independence: ORM allows for development of
database-independent applications, which can facilitate
seamless migration across different database platforms
without requiring significant code changes
 Easy to learn: ORM allows you to work with databases
using Java objects without writing SQL queries explicitly
 Streamlines database interactions: ORM reduces
boilerplate code and streamlines database interactions
 Simplifies maintenance: ORM simplifies maintenance with
automatic schema generation and higher-level query
languages

14. List the key components of Hibernate.

Hibernate is a Java framework that provides tools for accessing


and persisting data in a Java environment. It has many key
components, including:
Configuration, Session, SessionFactory, Criteria, Query, and
Transaction

15. Mention two components of Hibernate configuration object.


Database Connection:
The database connection component tells Hibernate how to
connect to the database. This information is typically stored in
a hibernate.properties file or a hibernate.cfg.xml file. The
hibernate.properties file is a text file that contains key-value
pairs. The hibernate.cfg.xml file is an XML file that contains the
same information as the hibernate.properties file, but in a more
structured format.
Class Mapping Setup:
The class mapping setup component tells Hibernate how to
map Java classes to database tables. This information is
typically stored in a hibernate.cfg.xml file. The
hibernate.cfg.xml file contains a list of mappings, each of which
maps a Java class to a database table.
These two components are essential for configuring
Hibernate. Without them, Hibernate would not be able to
connect to the database or map Java classes to database
tables.

16. How is SQL query created in Hibernate?


In Hibernate, you can create an SQL query using
the createSQLQuery() method of the Session interface. This
method returns an instance of the SQLQuery interface, which
allows you to execute native SQL queries. You can use
the SQLQuery interface to execute queries that are specific to
the database vendor but not supported by the Hibernate
API. For example, you can use it to execute query hints or
the CONNECT keyword in Oracle Database
17. What does HQL stand for?
HQL stands for Hibernate Query Language, which is an object-
oriented query language that is similar to SQL. HQL is used to
bridge the gap between object-oriented systems and relational
databases. HQL is an extension of SQL that uses objects instead
of table names, making it more object-oriented.
18. How can we add criteria to a SQL query?

To add criteria to a SQL query, you can:


1. Open the query in Design view
2. In the Query design grid, click the Criteria row of the field
where you want to add the criterion
3. Choose the type of criteria you want by right-clicking in
the grid and selecting the appropriate criteria from the
grid's context menu
4. Enter criteria into the row according to the type of criteria
you have chosen
5. Press ENTER

19. What is SessionFactory?


SessionFactory is a factory class for Session objects in
Hibernate that represents an instance of Hibernate. It maintains
the runtime metamodel, which includes persistent entities,
their attributes, associations, and mappings to relational
database tables. It also contains configuration that affects the
runtime behavior of Hibernate, and instances of services
20. Is Session a thread-safe object?
No, Session is not a thread-safe object. This means that if you
use the same Session object in multiple threads, you may run
into problems such as data corruption or unexpected behavior.
To avoid these problems, you should create a new Session
object for each thread. You can do this using the
sessionmaker() function.

You might also like