0% found this document useful (0 votes)
3 views21 pages

Adv Java

The document contains a series of questions and answers related to advanced Java topics, including JDBC, multithreading, JSP, servlets, and networking. Key concepts covered include JDBC API packages, thread management methods, servlet lifecycle, and differences between various Java components like Statement and PreparedStatement. Additionally, it includes example Java code snippets for database operations and explanations of networking protocols.

Uploaded by

pratiksavant2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

Adv Java

The document contains a series of questions and answers related to advanced Java topics, including JDBC, multithreading, JSP, servlets, and networking. Key concepts covered include JDBC API packages, thread management methods, servlet lifecycle, and differences between various Java components like Statement and PreparedStatement. Additionally, it includes example Java code snippets for database operations and explanations of networking protocols.

Uploaded by

pratiksavant2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

*Adv java

📄 Q1 from Question Paper 1

a) Write down 2 packages of JDBC API.

• java.sql
• javax.sql

b) What is yield( ) method?

• The yield() method pauses the current thread and allows other threads of the same
priority to execute. It’s a way to give up CPU voluntarily.

c) What is JDBC?

• JDBC (Java Database Connectivity) is an API that allows Java programs to connect
and interact with databases using SQL.

d) What is scriptlet tag?

• A scriptlet tag in JSP is <% %> and it is used to write Java code within HTML.

e) What is wait( ) and notify( ) in multithreading?

• wait() pauses the thread until another thread invokes notify() or notifyAll() on
the same object. These methods are used for inter-thread communication.

f) What is Networking?

• Networking refers to the process of connecting two or more computers to share


resources and data. In Java, it's achieved using classes from java.net.

g) What is Driver Manager class?

• DriverManager is a class in JDBC used to manage a list of database drivers and


establish a connection to a database.

h) What is ORM?

• ORM (Object Relational Mapping) is a technique to map Java objects to database


tables and vice versa. Frameworks like Hibernate use ORM.

i) What is Session?

• A session is a way to store information across multiple user requests. It is commonly


used in web applications to maintain state.

1
j) What is the role of Prepared Statement?

• A PreparedStatement is used to execute parameterized SQL queries. It improves


performance and prevents SQL injection.

📄 Q1 from Question Paper 2

a) Write down 2 methods of connection interface.

• createStatement()
• prepareStatement()

b) What is sleep() method in multithreading?

• sleep(milliseconds) is used to pause the execution of the current thread for a


specified time.

c) What is the method to set the thread priority?

• setPriority(int newPriority)

d) Write down 2 classes used in socket programming.

• Socket
• ServerSocket

e) What is IP address?

• An IP address is a unique string of numbers separated by periods that identifies each


computer using the Internet Protocol to communicate.

f) What is doGet( ) method of servlet?

• doGet() is used to handle HTTP GET requests from a client in a servlet.

g) What are the parameters of service() method of servlet.

• HttpServletRequest request, HttpServletResponse response

h) What is JSP?

• JSP (JavaServer Pages) is a technology used to create dynamic web content using
HTML and embedded Java code.

2
i) What is Hibernate?

• Hibernate is a Java ORM framework used for mapping Java objects to database
tables.

j) What is getConnection method?

• getConnection() is a static method of DriverManager used to establish a database


connection.

📄 Q1 from Question Paper 3

a) List types of ResultSet.

• TYPE_FORWARD_ONLY
• TYPE_SCROLL_INSENSITIVE
• TYPE_SCROLL_SENSITIVE

b) What is IP Address?

• An IP address is a unique number assigned to each device connected to a network.

c) What is JDBC?

• JDBC is an API for Java that allows the connection and execution of queries with
databases.

d) What is servlet?

• A servlet is a Java class used to handle requests and responses in a web application.

e) What is cookies?

• Cookies are small pieces of data stored on the client’s browser used to maintain
session information.

f) What is UDP?

• UDP (User Datagram Protocol) is a connectionless, fast transport layer protocol used
in networking.

g) What is thread?

• A thread is a lightweight sub-process, the smallest unit of processing in a Java


program.

3
h) What is socket?

• A socket is an endpoint for communication between two machines.

i) List the directives in JSP.

• <%@ page %>, <%@ include %>, <%@ taglib %>

j) What is networking?

• Networking is the communication between multiple computers or devices to share


data and resources.

✅ Q2 – Question Paper 1

Attempt any four of the following:

a) Explain life cycle of servlet.

Answer:
The servlet lifecycle is managed by the servlet container and involves:

1. Loading and Instantiation – Servlet class is loaded and instantiated.


2. Initialization (init()) – Called once when the servlet is first loaded.
3. Request Handling (service()) – Handles client requests.
4. Destruction (destroy()) – Called once before the servlet is removed from service.

b) Differentiate between Statement and PreparedStatement.

Answer:

Statement PreparedStatement

Compiles SQL every time Compiled once, reused

Less secure Prevents SQL Injection

Slower for repeated use Faster with repeated execution

c) Explain Inter Thread communication in Multithreading.

Answer:
It allows synchronized threads to communicate using wait(), notify(), and notifyAll().

4
• wait() – thread waits.
• notify() – wakes one waiting thread.
• notifyAll() – wakes all waiting threads.

Used for cooperation between threads (e.g., producer-consumer problem).

d) Explain JSP Architecture.

Answer:
JSP architecture follows MVC:

1. Client sends request.


2. JSP acts as view (presentation).
3. Servlet/Controller processes request.
4. JavaBeans/Model interacts with DB.
5. Response sent back to client.

e) Write a JDBC Program to Insert the record into patient table (Use
prepared statement).

Answer:

java
CopyEdit
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/hospital", "root",
"pass");
PreparedStatement pst = con.prepareStatement("INSERT INTO patient VALUES
(?, ?, ?)");
pst.setInt(1, 101);
pst.setString(2, "John");
pst.setInt(3, 45);
pst.executeUpdate();
System.out.println("Record Inserted");

✅ Q2 – Question Paper 2

a) What is statement? Explain the types of statements in JDBC.

Answer:
Statement is used to execute SQL queries.
Types:

1. Statement – Simple SQL queries.


2. PreparedStatement – Precompiled, parameterized queries.
3. CallableStatement – Executes stored procedures.

5
b) Explain thread life cycle with diagram.

Answer:
Thread Lifecycle states:

1. New – Created using Thread t = new Thread();


2. Runnable – Ready to run.
3. Running – Currently executing.
4. Blocked/Waiting – Waiting for resource.
5. Terminated – Execution completed.

c) What are the implicit objects in JSP? Explain any 4.

Answer:

1. request – for HTTP request.


2. response – for HTTP response.
3. session – maintains user session.
4. application – for shared data across pages.

d) Write down the difference between doGet() and doPost() method.

Answer:

doGet() doPost()

Sends data via URL Sends data in body

Less secure More secure

Limited data size Can send large data

e) Write a Java program to count number of records in a table.

Answer:

java
CopyEdit
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root",
"pass");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM student");

6
if(rs.next()) {
System.out.println("Total Records: " + rs.getInt(1));
}

✅ Q2 – Question Paper 3

a) List & explain all the interfaces used in JDBC.

Answer:

1. Driver – Loads JDBC drivers.


2. Connection – Connects to DB.
3. Statement – Executes SQL queries.
4. PreparedStatement – Executes parameterized queries.
5. ResultSet – Stores query result.
6. CallableStatement – Calls stored procedures.

b) Differentiate between HTTP servlet and Generic servlet.

Answer:

HTTPServlet GenericServlet

For HTTP requests only Protocol-independent

Extends HttpServlet Extends GenericServlet

Has doGet(), doPost() Has service()

c) Explain life cycle of JSP with suitable diagram.

Answer:
JSP lifecycle stages:

1. Translation – JSP → Servlet.


2. Compilation – Servlet compiled to class.
3. Loading – Servlet loaded into container.
4. Instantiation – Object is created.
5. Initialization – jspInit() method.
6. Request handling – _jspService() method.
7. Destruction – jspDestroy() method.

7
d) What is synchronization? Explain.

Answer:
Synchronization prevents multiple threads from accessing shared resources at the same time. It uses
the synchronized keyword.
Example:

java
CopyEdit
synchronized void printData() {
// code
}

1.

a) Explain JDBC Drivers with a suitable diagram

JDBC Drivers are used to connect Java applications to databases.

Types of JDBC Drivers:

1. Type 1: JDBC-ODBC Bridge Driver


o Uses ODBC driver to connect to the database.
o Deprecated in modern Java.
o Example: sun.jdbc.odbc.JdbcOdbcDriver
2. Type 2: Native API Driver
o Converts JDBC calls into native API calls (specific to DB).
o Platform dependent.
3. Type 3: Network Protocol Driver
o Uses a middleware server to translate JDBC calls.
o Flexible and portable.
4. Type 4: Thin Driver (Pure Java)
o Directly connects to the database using Java.
o Most efficient and widely used.

Diagram:

pgsql
Copy code
Java App
|
| (JDBC API)

JDBC Driver Manager

JDBC Driver (Type 1 / 2 / 3 / 4)

Database

8
b) Use of InetAddress class with example

InetAddress is used to represent IP addresses and host names.

Common Methods:

• getLocalHost() – Get local machine IP


• getByName(String host) – Get IP of given domain
• getHostAddress() – Get IP address
• getHostName() – Get host name

Example:
java
Copy code
import java.net.*;

public class InetDemo {


public static void main(String[] args) throws Exception {
InetAddress ip = InetAddress.getByName("www.google.com");

System.out.println("Host Name: " + ip.getHostName());


System.out.println("IP Address: " + ip.getHostAddress());
}
}

c) Differentiate between JSP and Servlet

Feature JSP Servlet

File Extension .jsp .java

Syntax HTML + Java code Pure Java code

Compilation Compiled into servlet Already written as servlet

Easy for designers Yes (HTML first) No (Java-heavy)

Performance Slightly slower initially Faster startup

Use Case View/Presentation logic Controller/Business logic

d) JDBC Program to delete students with names starting with 'm'


java
Copy code
import java.sql.*;

public class DeleteMStudents {


public static void main(String[] args) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");

9
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root",
"password");

String sql = "DELETE FROM student WHERE name LIKE 'm%'";


PreparedStatement pst = con.prepareStatement(sql);

int rows = pst.executeUpdate();


System.out.println(rows + " record(s) deleted.");
con.close();
}
}

e) JSP Program to display prime numbers between 1 to n

JSP File: prime.jsp


jsp
Copy code
<%@ page import="java.util.*" %>
<html>
<body>
<form method="post">
Enter n: <input type="number" name="n" />
<input type="submit" value="Show Primes" />
</form>

<%
String str = request.getParameter("n");
if(str != null){
int n = Integer.parseInt(str);

out.print("<h3>Prime numbers between 1 and " + n + ":</h3>");


for(int i = 2; i <= n; i++) {
boolean isPrime = true;
for(int j = 2; j <= i/2; j++) {
if(i % j == 0) {
isPrime = false;
break;
}
}
if(isPrime) out.print(i + " ");
}
}
%>
</body>
</html>

10
2- Q3: [4 × 4 = 16]

a) Explain Architecture of Hibernate:

Hibernate Architecture consists of:

• Configuration: Reads hibernate.cfg.xml or hibernate.properties.


• SessionFactory: Created once and used to create Session objects.
• Session: Represents a single-threaded unit of work.
• Transaction: Used to group database operations.
• Query: Used to retrieve data.
• Object-Relational Mapping (ORM): Maps Java classes to DB tables.

Diagram:

pgsql
CopyEdit
Application
|
SessionFactory
|
Session
| \
Transaction Query
|
Database

b) What is ResultSet in JDBC? Explain methods:

ResultSet is an interface in JDBC used to hold data retrieved from the database.

Important methods:

• next() – Moves the cursor to next row.


• getString(columnName) – Gets string from column.
• getInt(columnName) – Gets integer from column.
• close() – Closes the ResultSet.

c) Explain JSP Life Cycle with diagram:

JSP Life Cycle Stages:

1. Translation: JSP → Servlet.


2. Compilation: Servlet is compiled.
3. Loading: Loaded into memory.
4. Instantiation: Object is created.
5. Initialization: jspInit() is called.
6. Request Processing: jspService() is called.
7. Destroy: jspDestroy() is called.

11
Diagram:

scss
CopyEdit
JSP Page

Translation

Compilation

Servlet Class

Initialization (jspInit)

Request Handling (jspService)

Destroy (jspDestroy)

d) Java Program to print 100 to 1 using sleep():


java
CopyEdit
public class CountDown {
public static void main(String[] args) throws InterruptedException {
for (int i = 100; i >= 1; i--) {
System.out.println(i);
Thread.sleep(100); // sleep for 100 milliseconds
}
}
}

e) Java Program to create table student (Rno, Sname, Per):


java
CopyEdit
import java.sql.*;

public class CreateStudentTable {


public static void main(String[] args) {
try {
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDB", "root",
"password");
Statement stmt = con.createStatement();
String sql = "CREATE TABLE student (Rno INT, Sname VARCHAR(50),
Per FLOAT)";
stmt.executeUpdate(sql);
System.out.println("Table created successfully.");
} catch (Exception e) {
System.out.println(e);
}
}
}

12
-3 Q3: [4 × 4 = 16]

a) Explain Statement Interface:

Statement is used to execute static SQL queries. Methods:

• executeQuery(String sql) – Returns ResultSet.


• executeUpdate(String sql) – Performs insert/update/delete.
• close() – Closes the Statement.

b) Explain Thread Priority:

Java threads can be assigned a priority between 1 (MIN) to 10 (MAX).

• Default: 5 (NORM_PRIORITY)
• Use setPriority(int) and getPriority().
• Higher priority threads are scheduled first (but not guaranteed).

c) Difference between TCP and UDP Socket:


Feature TCP UDP

Type Connection-oriented Connection-less

Reliability Reliable (error checking) Not reliable

Speed Slower Faster

Use Case Web, Email Streaming, Gaming

d) Java Program to print "Hello Java" 10 times:


java
CopyEdit
public class HelloJava {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println("Hello Java");
}
}
}

e) Java Program to delete salary column from Emp table:


java
CopyEdit
import java.sql.*;

public class DeleteColumn {


public static void main(String[] args) {

13
try {
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDB", "root",
"password");
Statement stmt = con.createStatement();
String sql = "ALTER TABLE Emp DROP COLUMN salary";
stmt.executeUpdate(sql);
System.out.println("Salary column deleted.");
} catch (Exception e) {
System.out.println(e);
}
}
}

Q1.Q4) Attempt any four:


a) Scripting Elements of JSP:

1. Declarations (<%! %>) – Declare variables and methods.


2. Scriptlets (<% %>) – Java code that is executed.
3. Expressions (<%= %>) – Outputs values to the client.

b) Steps to connect to a database in Java (JDBC):

1. Load the driver class:

java
CopyEdit
Class.forName("com.mysql.cj.jdbc.Driver");

2. Create connection:

java
CopyEdit
Connection con = DriverManager.getConnection(url, user, password);

3. Create statement:

java
CopyEdit
Statement stmt = con.createStatement();

4. Execute query:

java
CopyEdit
ResultSet rs = stmt.executeQuery("SELECT * FROM tablename");

5. Close connection:

java
CopyEdit
con.close();

14
c) doGet() vs doPost() methods:
doGet() doPost()

Sends data via URL Sends data in request body

Limited data size No size limitation

Less secure More secure

Used for fetching data Used for updating/sending data

d) JSP Program – Factorial of a number:


jsp
CopyEdit
<%@ page language="java" %>
<html>
<body>
<%
int n = 5; // example number
int fact = 1;
for(int i = 1; i <= n; i++) {
fact *= i;
}
out.println("Factorial of " + n + " is: " + fact);
%>
</body>
</html>

e) Servlet to display employee details:


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

public class DisplayEmployee extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDB", "root",
"pass");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM employee");

out.println("<table
border='1'><tr><th>ENO</th><th>ENAME</th><th>SAL</th><th>DESIGN</th></tr>")
;
while(rs.next()) {
out.println("<tr><td>" + rs.getInt("eno") + "</td><td>" +
rs.getString("ename") +
"</td><td>" + rs.getFloat("sal") + "</td><td>"
+ rs.getString("design") + "</td></tr>");

15
}
out.println("</table>");
} catch(Exception e) {
out.println("Error: " + e);
}
}
}

Q5) Write short notes on any two:


a) GenericServlet vs HttpServlet:

• GenericServlet – Protocol-independent, used for any service (not just HTTP).


• HttpServlet – Extension of GenericServlet for handling HTTP-specific requests like GET,
POST.

b) Cookies:

• Small pieces of data stored on the client-side.


• Used for session tracking.
• Can store username, preferences, etc.

c) ResultSet Interface:

• Used to hold and access data retrieved via SQL queries.


• Cursor-based navigation using next(), previous(), etc.

Q2.Q4) Attempt any four:


a) States of Object in Hibernate:

1. Transient – New object, not yet saved.


2. Persistent – Saved and associated with session.
3. Detached – Previously persistent, now session closed.
4. Removed – Marked for deletion.

b) Session Tracking in Servlet:

Techniques:

1. Cookies
2. Hidden Form Fields
3. URL Rewriting
4. HttpSession

16
c) Thread Priority:

• Java allows setting thread priority from 1 to 10.


• Default: 5 (NORM_PRIORITY)
• Set using:

java
CopyEdit
thread.setPriority(Thread.MAX_PRIORITY);

d) JSP to accept and greet user:


jsp
CopyEdit
<html>
<body>
<form method="post">
Enter your name: <input type="text" name="uname">
<input type="submit" value="Submit">
</form>
<%
String name = request.getParameter("uname");
if(name != null)
out.println("Welcome " + name + "!");
%>
</body>
</html>

e) Java Program to display IP Address:


java
CopyEdit
import java.net.*;

public class IPDisplay {


public static void main(String[] args) throws Exception {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("IP Address: " + ip.getHostAddress());
}
}

Q5) Short notes on any two:


a) Connection Interface:

• Part of JDBC.
• Used to establish connection with database using:

java
CopyEdit
Connection con = DriverManager.getConnection(url, user, pass);

17
b) Runnable Interface:

• Interface used to create threads using:

java
CopyEdit
class MyThread implements Runnable {
public void run() {
// code
}
}

c) Thread Synchronization:

• Prevents multiple threads from accessing the same resource.


• Achieved using synchronized keyword.

Q3.

Q4. Attempt any FOUR of the following:

a) Write a java program to display IP Address of a Machine.


java
CopyEdit
import java.net.*;

public class IPAddress {


public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println("IP Address: " + ip.getHostAddress());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}

b) Explain Architecture of Hibernate.

Answer: Hibernate is an ORM (Object Relational Mapping) framework that maps Java classes to
database tables.
Hibernate Architecture includes:

1. Configuration – hibernate.cfg.xml or annotations.


2. SessionFactory – A factory for session objects.
3. Session – Provides CRUD operations.
4. Transaction – Used for database transaction handling.
5. Query – HQL or SQL queries.

18
6. Persistent Objects – Java classes mapped to database tables.

Diagram:

pgsql
CopyEdit
Application
|
Configuration --> SessionFactory
|
Session --> Transaction
|
Database

c) Explain life cycle of servlet with suitable diagram.

Answer: Servlet lifecycle is managed by the servlet container and includes the following phases:

1. Loading and Instantiation – Servlet class is loaded and instance is created.


2. Initialization (init() method) – Called once when servlet is initialized.
3. Request Handling (service() method) – Called for each client request.
4. Destruction (destroy() method) – Called before servlet is removed.

Diagram:

rust
CopyEdit
Client Request
|
[Web Container]
|
-> init()
-> service()
-> destroy()

d) What is multithreading? Explain.

Answer: Multithreading is a process of executing multiple threads simultaneously. It helps in


performing many tasks at the same time, improving performance.

Advantages:

• Efficient CPU usage


• Faster execution
• Better performance for multitasking applications

Example:

java
CopyEdit
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");

19
}
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}

e) Write a java servlet program to accept name from user & display on browser [use HTML].

HTML Form:

html
CopyEdit
<form action="NameServlet" method="post">
Enter Name: <input type="text" name="username">
<input type="submit" value="Submit">
</form>

Servlet Code:

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

public class NameServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
out.println("<h1>Hello, " + name + "</h1>");
}
}

Q5. Write a short note on Any TWO of the following:

a) notify(), notifyAll() & wait()

Answer: These are used in multithreading for thread communication.

• wait() – Causes the current thread to wait until another thread invokes notify() or
notifyAll().
• notify() – Wakes up a single thread that is waiting on the object's monitor.
• notifyAll() – Wakes up all threads that are waiting on the object's monitor.

Example:

java
CopyEdit
synchronized(obj) {
obj.wait(); // waits

20
obj.notify(); // notifies one
obj.notifyAll(); // notifies all
}

b) Applications of Spring.

Answer: Spring is a powerful Java framework used for building enterprise-level applications.

Applications:

• Web applications using Spring MVC.


• Microservices using Spring Boot.
• Dependency injection and AOP.
• Data access using Spring Data JPA.
• Security with Spring Security.

c) Connection Interface.

Answer: Connection interface in Java SQL package represents a connection (session) with a
database.

Important methods:

• createStatement()
• prepareStatement()
• commit()
• rollback()
• close()

Example:

java
CopyEdit
Connection con = DriverManager.getConnection(url, user, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");

21

You might also like