1. What are Servlets? Explain database connectivity using Java Servlets.
Answer:
Servlets are Java-based server-side programs that handle client requests and generate dynamic web
content. They run within a servlet container such as Apache Tomcat and extend the capabilities of
web servers.
Database Connectivity Using Java Servlets:
1. Load the JDBC driver.
2. Establish a connection using DriverManager.getConnection().
3. Create a Statement or PreparedStatement object.
4. Execute queries using executeQuery() or executeUpdate().
5. Process the results and close the connection.
Example Code:
java
CopyEdit
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DBServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
out.println(rs.getInt(1) + " " + rs.getString(2) + "<br>");
}
con.close();
} catch (Exception e) {
out.println(e);
2. What is JSP? Explain the JSP environment.
Answer:
JavaServer Pages (JSP) is a technology used to develop dynamic web pages using Java. It allows
embedding Java code inside HTML using special tags like <% %>. JSP is converted into a servlet before
execution.
JSP Environment:
• JSP Engine: Converts JSP pages into servlets.
• Servlet Container: Hosts and manages servlets.
• Request and Response Objects: Facilitate communication between the client and server.
• Built-in JSP Objects: request, response, session, application, etc.
• Custom Tags and EL: Enhance reusability and simplify dynamic content generation.
3. What are threads in Java? What are the advantages of multithreaded programming?
Answer:
A thread in Java is a lightweight subprocess that runs independently. It allows concurrent execution
within a program.
Advantages of Multithreading:
1. Improved Performance: Multiple tasks execute simultaneously, enhancing efficiency.
2. Better CPU Utilization: Ensures the processor is not idle.
3. Faster Execution: Reduces response time in applications like gaming and web servers.
4. Concurrency: Allows handling multiple requests at once.
Example Code for Thread Creation:
java
CopyEdit
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
public static void main(String args[]) {
MyThread t = new MyThread();
t.start();
4. Explain exception handling in Java. How does Java handle strings?
Answer:
Exception handling in Java is done using try, catch, finally, throw, and throws to manage runtime
errors gracefully.
Example:
java
CopyEdit
try {
int num = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("Execution completed.");
Handling Strings in Java:
• String Creation: String str = "Hello";
• Concatenation: str1.concat(str2);
• Comparison: str1.equals(str2);
• Substring Extraction: str.substring(0, 5);
• Mutable Strings: Use StringBuilder or StringBuffer.
5. What is an Applet? Explain the term Driver.
Answer:
An Applet is a Java program that runs inside a web browser. It extends java.applet.Applet and is
embedded using <applet> tags.
Example Applet Code:
java
CopyEdit
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 50, 50);
A Driver is a software component that enables Java to interact with databases via JDBC. Example:
com.mysql.cj.jdbc.Driver for MySQL.
6. What is the difference between AWT and Swing?
Feature AWT (Abstract Window Toolkit) Swing
Look & Feel OS-dependent OS-independent
Components Heavyweight Lightweight
Flexibility Limited More customizable
Performance Slower Faster
7. What is the lifecycle of a Servlet?
Answer:
1. Loading: The servlet class is loaded.
2. Initialization (init()): Called once when the servlet is created.
3. Request Handling (service()): Handles client requests.
4. Destruction (destroy()): Called when the servlet is unloaded.
Example:
java
CopyEdit
public void init() { System.out.println("Servlet Initialized"); }
public void service() { System.out.println("Processing Request"); }
public void destroy() { System.out.println("Servlet Destroyed"); }
8. What is event handling in Java? Explain with an example.
Answer:
Event handling allows Java programs to respond to user actions like button clicks.
Example:
java
CopyEdit
import java.awt.*;
import java.awt.event.*;
public class EventDemo extends Frame implements ActionListener {
Button b;
EventDemo() {
b = new Button("Click Me");
b.setBounds(50, 50, 80, 30);
b.addActionListener(this);
add(b);
setSize(300, 300);
setLayout(null);
setVisible(true);
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
public static void main(String args[]) {
new EventDemo();
9. What is polymorphism in Java?
Answer:
Polymorphism allows methods to have multiple implementations.
Types:
• Compile-time polymorphism (Method Overloading):
java
CopyEdit
class Math {
int add(int a, int b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
• Runtime polymorphism (Method Overriding):
java
CopyEdit
class Parent { void show() { System.out.println("Parent"); } }
class Child extends Parent { void show() { System.out.println("Child"); } }
10. Explain TCP/IP-based socket programming in Java.
Answer:
Sockets allow communication between devices over a network.
Example Client-Server Communication: Server:
java
CopyEdit
ServerSocket server = new ServerSocket(5000);
Socket socket = server.accept();
Client:
java
CopyEdit
Socket socket = new Socket("localhost", 5000);
11. What is an Interface in Java?
An interface is an abstract type that defines a contract for classes.
Example:
java
CopyEdit
interface Animal { void makeSound(); }
class Dog implements Animal { public void makeSound() { System.out.println("Bark!"); } }
12. What is JDBC?
Java Database Connectivity (JDBC) is an API for database interaction.
13. What is HTML? Explain its structure.
HTML (Hypertext Markup Language) structures web pages using tags like <html>, <head>, <body>,
etc.
14. What is an Array in Java?
An array is a collection of elements of the same type, accessed via indexing.
15. What is a Vector in Java?
A Vector is a dynamic array that grows automatically.