0% found this document useful (0 votes)
15 views15 pages

Java Question Bank with Answers

The document is a comprehensive Java question bank that includes both short and detailed answers to various topics related to Java programming. It covers fundamental concepts such as objects, classes, inheritance, polymorphism, and exception handling, along with practical examples and syntax explanations. The content serves as a study guide for understanding Java programming principles and practices.

Uploaded by

pankaj9653292835
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)
15 views15 pages

Java Question Bank with Answers

The document is a comprehensive Java question bank that includes both short and detailed answers to various topics related to Java programming. It covers fundamental concepts such as objects, classes, inheritance, polymorphism, and exception handling, along with practical examples and syntax explanations. The content serves as a study guide for understanding Java programming principles and practices.

Uploaded by

pankaj9653292835
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

Java Question Bank - Short + Detailed Answers

Generated: 2025-10-02 05:18:06

Java Question Bank - Short + Detailed Answers


Generated: 2025-10-02 05:18:05

Table of Contents

1. Write short note on Objects and classes.


2. Write a short note on Data abstraction and encapsulation.
3. Write a short note on Inheritance.
4. Write a short note on Polymorphism.
5. Write a short note on Message Communication.
6. State the benefits of Object-Oriented Programming Language.
7. List and explain any 5 features of Java.
8. Explain in detail the syntax of the main method.
9. Explain the structure of Java program?
10. Explain with diagram different data type in Java?
11. Write a short note on scope of variable.
12. Explain any three types of operators?
13. List and explain any 5 mathematical functions.
14. Explain the following proper syntax and example: if else?
15. Explain the following proper syntax and example: else if ladder?
16. Explain the following proper syntax and example: switch case?
17. Explain the following proper syntax and example: while?
18. Explain the following proper syntax and example: do while?
19. Explain the following proper syntax and example: for?
20. Explain with example class structure?
21. Explain how to create objects & access class members?
22. Write a short note on Constructors.
23. Write a short note on Method Overloading.
24. Describe in detail types of inheritance?
25. Write a short note on Overriding Method.
26. List and explain any 5-string function.
27. Explain with an example how to define and use an interface?
28. State the naming convention for packages and explain how to create packages.
29. State the difference between multi-threading and multitasking.
30. Explain with an example how to create thread?
31. Explain with diagram Life Cycle of Thread?
32. What is an exception? List any 5 common Java Exceptions.
33. Explain different types of panes used in swing?
34. What is the purpose of using the getContentPane() in swing program ?
35. Write a short note on JFC?
36. How Are Swing Components Different from AWT Components?
37. Explain any 5 Swing features.
38. Write a short note on JFrame?
39. Explain with an example JScrollPane.
40. What is JTabbed Pane ? Explain with an example.
41. Explain the importance of JComponent Class.
42. Write a Swing program containing a button with the caption “Now” and a text field. On click of
button, current date and time to be displayed in the text field?
43. State and explain any three classes used to create Menus in Swing?
44. How do you create a JMenu and add it to a JMenuBar inside a JFrame?
45. List and explain any three Text-Entry Components.
46. Write a swing program containing three text fields. The first text field accepts the first name,
second accepts last name and third displays full name on click of a button.
47. Write a program containing three text fields, out of which third is disabled. It also contains 4
buttons representing +, -, *, and / operation. The first two textbox accepts two numbers, on click
of button, answer displayed in third text field.
48. What are the components of JDBC?
49. Explain the importance of the following methods: [Link], [Link],
[Link]
50. Explain any two drivers of JDBC.
51. Explain different types of JDBC Drivers.
52. Outline the steps to access a database using JDBC.
53. Explain the following methods and state the class/interface to which they belong to:
executeUpdate(), getColumnCount(), getString()
54. Write a JDBC program that accepts a table name and displays a total number of records present in
it.
55. Write a JDBC program that accepts account numbers from the user and obtains the name and current
balance from the Customer table.
56. Write a JDBC program to accept and table name and to display the total number of columns and
total number of records from it.
57. Write a JDBC program to accept the name of a student, find the student in the table and based on
the date of birth calculate and display the student’s age.
58. State and explain any two exception classes related to JDBC?
59. Explain with an example how to create and use Prepared Statement.
60. How are SQL joins executed using JDBC?
61. Explain how a Stored Procedure can be called from JDBC.
62. Write a short note on Life Cycle of a Thread?
63. Explain with an example how a Thread can be created using Runnable Class.
64. State and explain the methods used for Thread Synchronization?
65. Explain with an example how Thread can be created using Thread Class.

Answers

1. Write short note on Objects and classes.

Short Answer:
Objects are instances of classes; classes are blueprints defining state (fields) and behavior
(methods).

Detailed Answer:
Objects are concrete instances that hold state and expose behavior. A class is a blueprint that
defines fields (attributes) and methods (behaviors). Example:
class Car { String color; void drive() { } }
Car c = new Car(); // c is an object.

---

2. Write a short note on Data abstraction and encapsulation.

Short Answer:
Abstraction hides complexity exposing essential features; encapsulation bundles data with methods
and restricts access via access modifiers.

Detailed Answer:
Abstraction means exposing only necessary features of an object while hiding implementation details.
Encapsulation ties data (fields) and methods into a single unit and uses access modifiers (private,
protected, public) to protect state. Example: private int balance; public int getBalance() { return
balance; }

---

3. Write a short note on Inheritance.

Short Answer:
Inheritance allows a class (subclass) to acquire properties and methods of another class
(superclass) enabling code reuse.

Detailed Answer:
Inheritance models an 'is-a' relationship. A subclass reuses code from a superclass and can extend
or override behavior. Example:
class Animal { void eat() {} }
class Dog extends Animal { void bark() {} }

---

4. Write a short note on Polymorphism.

Short Answer:
Polymorphism allows one interface to be used for different underlying forms — compile-time
(overloading) and run-time (overriding).

Detailed Answer:
Polymorphism allows treating objects of different classes through a common interface. Compile-time
polymorphism (method overloading) resolves by signature, runtime polymorphism (method overriding)
uses dynamic dispatch. Example: Animal a = new Dog(); [Link](); // Dog's eat if overridden.

---

5. Write a short note on Message Communication.

Short Answer:
Message communication in OOP is how objects communicate by calling methods and passing data
(parameters/return values).

Detailed Answer:
Objects communicate by invoking methods on one another and passing arguments. This 'message passing'
decouples sender and receiver and supports loose coupling.

---

6. State the benefits of Object-Oriented Programming Language.

Short Answer:
Benefits include modularity, reusability, maintainability, scalability and easier mapping to real-
world problems.

Detailed Answer:
OOP improves modularity by grouping related code, enhances reusability via inheritance and
composition, simplifies maintenance by encapsulation, and makes systems easier to model and extend.

---

7. List and explain any 5 features of Java.

Short Answer:
Java features: Platform independence, Object-oriented, Robust (exception handling), Secure
(sandbox), Multithreaded.

Detailed Answer:
Java is platform-independent via bytecode and JVM, strongly typed with automatic memory management
(garbage collector), supports multithreading, has rich standard libraries, and built-in security
features like the sandbox model.

---

8. Explain in detail the syntax of the main method.

Short Answer:
public static void main(String[] args) — entry point; public: accessible, static: callable without
object, void: no return, String[] args: command-line args.

Detailed Answer:
public: accessible by JVM; static: JVM calls it without object; void: returns nothing; main: method
name expected by JVM; String[] args: command-line arguments. Signature variations allowed (String...
args) and 'throws' can be added.

---

9. Explain the structure of Java program?

Short Answer:
A Java program has package declaration, import statements, class declaration and a main method (or
other entry points).

Detailed Answer:
Typical structure: package declaration, import statements, class declaration with fields,
constructors, methods, and an optional main method. Source file name should match public class name.

---

10. Explain with diagram different data type in Java?

Short Answer:
Primitive types (byte, short, int, long, float, double, char, boolean) and reference types (objects,
arrays, interfaces).

Detailed Answer:
Primitive types store simple values (boolean, byte, char, short, int, long, float, double).
Reference types point to objects (arrays, class instances). Size and range differ per type; use
wrapper classes (Integer, Double) when object behavior is needed.

---

11. Write a short note on scope of variable.

Short Answer:
Scope defines visibility: local variables (method/block), instance variables (object), class/static
variables (class-level).

Detailed Answer:
Local variables: declared inside methods/blocks, lifetime is method execution; Instance variables:
belong to object, lifetime is object life; Static/class variables: shared across all instances and
loaded with class.

---

12. Explain any three types of operators?

Short Answer:
Arithmetic, relational (comparison), logical operators — used for math, comparisons, and boolean
logic respectively.

Detailed Answer:
Arithmetic (+, -, *, /, %), Relational (>, <, >=, <=, ==, !=) for comparisons, Logical (&&, ||, !)
for boolean logic. Additionally assignment, bitwise and ternary exist.

---

13. List and explain any 5 mathematical functions.

Short Answer:
Java Math class functions: abs(), pow(), sqrt(), max(), min(), round(), ceil(), floor().

Detailed Answer:
[Link](x) - absolute value; [Link](a,b) - a raised to b; [Link](x) - square root;
[Link](a,b) - maximum; [Link](x) - nearest integer. Use Math class static methods.
---

14. Explain the following proper syntax and example: if else?

Short Answer:
if(condition) { //true block } else { //false block } — executes one of two branches.

Detailed Answer:
Syntax:
if (condition) {
// executed when condition true
} else {
// executed when condition false
}
Example:
int x=10; if(x%2==0) [Link]("even"); else [Link]("odd");

---

15. Explain the following proper syntax and example: else if ladder?

Short Answer:
else if ladder allows checking multiple conditions sequentially; first true branch executes.

Detailed Answer:
Syntax using multiple conditions:
if (cond1) {...} else if (cond2) {...} else {...}
Example: grade calculator with ranges using else-if ladder.

---

16. Explain the following proper syntax and example: switch case?

Short Answer:
switch(expression) { case x: ...; break; default: ... } — selects branch based on discrete values.

Detailed Answer:
switch(expression) {
case 1: // statements; break;
case 2: // statements; break;
default: // statements;
}
Note: from Java 7+, switch supports String. Use 'break' to prevent fall-through; labels and enhanced
switch exist in newer Java.

---

17. Explain the following proper syntax and example: while?

Short Answer:
while(condition) { //body } — repeats while condition is true; checks before each iteration.

Detailed Answer:
while(condition) {
// repeated until condition false
}
Example: int i=0; while(i<5){ [Link](i); i++; }

---

18. Explain the following proper syntax and example: do while?


Short Answer:
while(condition) { //body } — repeats while condition is true; checks before each iteration.

Detailed Answer:
while(condition) {
// repeated until condition false
}
Example: int i=0; while(i<5){ [Link](i); i++; }

---

19. Explain the following proper syntax and example: for?

Short Answer:
for(init; condition; update) { //body } — compact loop with init, test and update.

Detailed Answer:
for(initialization; condition; update) {
// body
}
Example: for(int i=0;i<10;i++) [Link](i); // traditional for. Enhanced for: for(Type x:
collection) { }

---

20. Explain with example class structure?

Short Answer:
A class contains fields, constructors, methods, and nested types; access modifiers control
visibility.

Detailed Answer:
public class MyClass {
// fields
private int x;
// constructors
public MyClass(int x){ this.x=x; }
// methods
public void setX(int x){ this.x=x; }
}
Explain members and visibility.

---

21. Explain how to create objects & access class members?

Short Answer:
Use new ClassName() to create objects; access members with [Link] or [Link]().

Detailed Answer:
Create: MyClass obj = new MyClass(10); Access fields/methods: [Link](); Static members:
[Link](); Use dot operator.

---

22. Write a short note on Constructors.

Short Answer:
Constructors initialize new objects; they have the same name as class and no return type.

Detailed Answer:
Constructors initialize object state. Default constructor provided if none defined. Overloaded
constructors allow different initialization. Example:
public Person() {}
public Person(String name) { [Link] = name; }

---

23. Write a short note on Method Overloading.

Short Answer:
Same method name with different parameter lists within the same class (compile-time polymorphism).

Detailed Answer:
Overloading allows multiple methods with same name but different parameter lists
(type/number/order). Compiler resolves calls at compile time. Useful for convenience methods.

---

24. Describe in detail types of inheritance?

Short Answer:
Single, Multilevel, Hierarchical, Multiple (not supported by classes), Hybrid — Java supports
interfaces for multiple inheritance of type.

Detailed Answer:
Single inheritance: Child extends one parent. Multilevel: A->B->C. Hierarchical: One parent,
multiple children. Java classes can't do multiple inheritance directly; use interfaces instead.
Hybrid is combination of above.

---

25. Write a short note on Overriding Method.

Short Answer:
Overriding provides a subclass implementation for a superclass method with same signature (runtime
polymorphism).

Detailed Answer:
Overriding replaces superclass method implementation in subclass. Use @Override annotation to help
compiler. Rules: same signature, compatible return type, not more restrictive access, can't reduce
checked exceptions.

---

26. List and explain any 5-string function.

Short Answer:
Common methods: length(), charAt(), substring(), indexOf(), toLowerCase(), toUpperCase(), replace().

Detailed Answer:
length(): returns length; charAt(index): char; substring(start,end): extract; indexOf(str): position
or -1; replace(old,new): replace chars/strings. Examples: "hello".substring(1,4) -> "ell".

---

27. Explain with an example how to define and use an interface?

Short Answer:
Interface declares method signatures; classes implement interfaces and provide method bodies;
supports multiple inheritance of type.

Detailed Answer:
Define: public interface Vehicle { void start(); }
Implement: class Car implements Vehicle { public void start(){...} }
Interfaces can have default and static methods since Java 8, and private methods since Java 9.
---

28. State the naming convention for packages and explain how to create packages.

Short Answer:
Use reverse domain names (e.g., [Link]). Create with 'package' keyword and place in
corresponding directory.

Detailed Answer:
Convention: reverse domain ([Link]). Create package using 'package [Link];' at top
of .java file. Directory structure must match package name; compile/run with correct classpath.

---

29. State the difference between multi-threading and multitasking.

Short Answer:
Multithreading: multiple threads in a single process; multitasking: multiple processes concurrently
on CPU.

Detailed Answer:
Multithreading: concurrent threads within same process sharing memory. Multitasking: multiple
processes/tasks, possibly by OS. Threads are lighter and faster to create than processes.

---

30. Explain with an example how to create thread?

Short Answer:
Create thread by extending Thread class or implementing Runnable and passing to a Thread instance.

Detailed Answer:
Example using Thread class: class MyThread extends Thread { public void run(){
[Link]("running"); } } MyThread t = new MyThread(); [Link]();

---

31. Explain with diagram Life Cycle of Thread?

Short Answer:
States: New, Runnable, Running, Waiting/Blocked, Timed_Waiting, Terminated.

Detailed Answer:
Explain states: New (created), Runnable (ready to run), Running (executing), Blocked/Waiting
(waiting for monitor or condition), Timed_Waiting (sleep, wait with timeout), Terminated (finished).
JVM scheduler moves between states.

---

32. What is an exception? List any 5 common Java Exceptions.

Short Answer:
An exception is an event disrupting normal flow; common exceptions: NullPointerException,
ArrayIndexOutOfBoundsException, ClassNotFoundException, SQLException, IOException.

Detailed Answer:
Exception: abnormal event during program execution. Checked exceptions (compile-time) must be
handled or declared (e.g., IOException), unchecked are runtime (NullPointerException). Example list:
NullPointerException, ArrayIndexOutOfBoundsException, ClassNotFoundException, SQLException,
IOException.

---
33. Explain different types of panes used in swing?

Short Answer:
JFrame, JPanel, JTabbedPane, JScrollPane, JSplitPane, JLayeredPane — different container panes for
layout and components.

Detailed Answer:
Common container panes:
- JFrame: top-level window
- JPanel: generic lightweight container for layout
- JScrollPane: provides scrolling
- JTabbedPane: multiple tabs
- JSplitPane: split view
- JLayeredPane: overlapping components

---

34. What is the purpose of using the getContentPane() in swing program ?

Short Answer:
getContentPane() returns the content pane of top-level containers, where components should be added
in older Swing code.

Detailed Answer:
getContentPane() returns the Container to which components should be added in older Swing code.
Since Java 5, you can add components directly to JFrame which delegates to content pane. It allows
layout management and adding components.

---

35. Write a short note on JFC?

Short Answer:
Java Foundation Classes (JFC) include Swing, AWT, and other GUI-related APIs.

Detailed Answer:
Java Foundation Classes (JFC) is an umbrella for GUI APIs: AWT, Swing, Accessibility and Drag-and-
Drop. It standardizes GUI development in Java.

---

36. How Are Swing Components Different from AWT Components?

Short Answer:
Swing is lightweight (drawn in Java), more flexible, richer components; AWT uses native OS peers.

Detailed Answer:
Swing components are lightweight (drawn by Java), consistent across platforms, support pluggable
look-and-feel, and provide richer functionality compared to heavyweight AWT components reliant on
native peers.

---

37. Explain any 5 Swing features.

Short Answer:
Pluggable look-and-feel, lightweight components, MVC architecture, double buffering, rich set of
components.

Detailed Answer:
Features: pluggable look-and-feel, lightweight components, rich set of GUI widgets, support for MVC,
event-driven programming and double buffering for smooth rendering.
---

38. Write a short note on JFrame?

Short Answer:
JFrame is a top-level window with border, title and close operations used as main application
window.

Detailed Answer:
JFrame is a top-level window with decorations; typical usage: JFrame frame = new JFrame("Title");
[Link](JFrame.EXIT_ON_CLOSE); [Link](400,300);
[Link](true);

---

39. Explain with an example JScrollPane.

Short Answer:
JScrollPane provides scrollbars for a component when its size exceeds viewport.

Detailed Answer:
Wrap a component inside JScrollPane: JTextArea ta = new JTextArea(); JScrollPane sp = new
JScrollPane(ta); [Link](sp); Scrollbars appear automatically when needed.

---

40. What is JTabbed Pane ? Explain with an example.

Short Answer:
JTabbedPane allows switching between panels via tabs.

Detailed Answer:
JTabbedPane tabbedPane = new JTabbedPane(); [Link]("Tab1", panel1);
[Link]("Tab2", panel2); [Link](tabbedPane);

---

41. Explain the importance of JComponent Class.

Short Answer:
JComponent is the base class for all Swing components providing common functionality like painting
and event handling.

Detailed Answer:
JComponent is the base class for Swing components providing painting, event handling, double
buffering and property change support. Custom components extend JComponent and override
paintComponent().

---

42. Write a Swing program containing a button with the caption “Now” and a text field. On click of
button, current date and time to be displayed in the text field?

Short Answer:
Use JButton and JTextField; add ActionListener to button to set [Link](new
Date().toString()).

Detailed Answer:
Example:
JButton btn = new JButton("Now"); JTextField tf = new JTextField(20);
[Link](e -> [Link](new [Link]().toString()));
Add to frame and show.
---

43. State and explain any three classes used to create Menus in Swing?

Short Answer:
JMenuBar, JMenu, JMenuItem.

Detailed Answer:
JMenuBar holds menus, JMenu represents a menu, JMenuItem represents selectable items. Use these to
build menu systems in Swing.

---

44. How do you create a JMenu and add it to a JMenuBar inside a JFrame?

Short Answer:
JFrame is a top-level window with border, title and close operations used as main application
window.

Detailed Answer:
JFrame is a top-level window with decorations; typical usage: JFrame frame = new JFrame("Title");
[Link](JFrame.EXIT_ON_CLOSE); [Link](400,300);
[Link](true);

---

45. List and explain any three Text-Entry Components.

Short Answer:
JTextField, JPasswordField, JTextArea.

Detailed Answer:
JTextField for single-line input, JPasswordField for masked input, JTextArea for multi-line text
input (usually inside JScrollPane).

---

46. Write a swing program containing three text fields. The first text field accepts the first name,
second accepts last name and third displays full name on click of a button.

Short Answer:
Short answer: See detailed section below.

Detailed Answer:
Detailed answer placeholder.

---

47. Write a program containing three text fields, out of which third is disabled. It also contains 4
buttons representing +, -, *, and / operation. The first two textbox accepts two numbers, on click
of button, answer displayed in third text field.

Short Answer:
Use setEnabled(false) on third field; add ActionListeners to operation buttons to compute and
display result.

Detailed Answer:
Disable third via [Link](false) or setEditable(false). Implement ActionListeners for buttons
that parse numbers from tf1 and tf2, perform arithmetic and display in tf3.

---
48. What are the components of JDBC?

Short Answer:
JDBC components: Driver, DriverManager, Connection, Statement/PreparedStatement, ResultSet,
SQLException.

Detailed Answer:
DriverManager loads drivers and manages connections, Connection represents DB session,
Statement/PreparedStatement execute SQL, ResultSet holds query results, SQLException handles DB
errors.

---

49. Explain the importance of the following methods: [Link], [Link],


[Link]

Short Answer:
[Link] loads the JDBC driver class; [Link] establishes DB connection;
createStatement creates a Statement for SQL execution.

Detailed Answer:
[Link]("[Link]") loads the driver class which registers with DriverManager.
[Link](url,user,pass) returns a Connection. [Link]()
creates a Statement to execute SQL queries.

---

50. Explain any two drivers of JDBC.

Short Answer:
Type 2 (Native-API/partly Java), Type 4 (Pure Java/Thin driver).

Detailed Answer:
Type 2 driver uses native client libraries to interact with database (faster but platform
dependent). Type 4 driver is a pure Java driver that communicates directly with DB protocol
(preferred for portability).

---

51. Explain different types of JDBC Drivers.

Short Answer:
Four types: Type 1 (JDBC-ODBC bridge), Type 2 (Native-API), Type 3 (Network Protocol), Type 4 (Thin,
pure Java).

Detailed Answer:
Type 1: JDBC-ODBC bridge (legacy), Type 2: Native API partly Java, Type 3: Network Protocol driver
communicates with middleware, Type 4: Pure Java (direct DB protocol).

---

52. Outline the steps to access a database using JDBC.

Short Answer:
Load driver, get connection, create statement, execute query/update, process ResultSet, close
resources.

Detailed Answer:
1. Load driver class
2. Get Connection via DriverManager
3. Create Statement or PreparedStatement
4. Execute query/update
5. Process ResultSet
6. Close ResultSet, Statement, Connection in finally block or use try-with-resources.

---

53. Explain the following methods and state the class/interface to which they belong to:
executeUpdate(), getColumnCount(), getString()

Short Answer:
Interface declares method signatures; classes implement interfaces and provide method bodies;
supports multiple inheritance of type.

Detailed Answer:
Define: public interface Vehicle { void start(); }
Implement: class Car implements Vehicle { public void start(){...} }
Interfaces can have default and static methods since Java 8, and private methods since Java 9.

---

54. Write a JDBC program that accepts a table name and displays a total number of records present in
it.

Short Answer:
Use SELECT COUNT(*) FROM tableName via Statement and read result from ResultSet.

Detailed Answer:
Use a PreparedStatement to avoid SQL injection: SELECT COUNT(*) FROM ? is not allowed for table
name; use validation or dynamic SQL with whitelist. Execute query and read integer from ResultSet.

---

55. Write a JDBC program that accepts account numbers from the user and obtains the name and current
balance from the Customer table.

Short Answer:
Parameterized query using PreparedStatement: SELECT name, balance FROM Customer WHERE accno = ?.

Detailed Answer:
Use PreparedStatement: SELECT name,balance FROM Customer WHERE accno = ?; set parameter with
[Link](1, accno); executeQuery and read from ResultSet.

---

56. Write a JDBC program to accept and table name and to display the total number of columns and
total number of records from it.

Short Answer:
Use [Link]() for columns and SELECT COUNT(*) for records.

Detailed Answer:
Get ResultSetMetaData rsmd = [Link](); int cols = [Link](); For rows use SELECT
COUNT(*) or iterate ResultSet to count. Efficient: use COUNT(*) for record count.

---

57. Write a JDBC program to accept the name of a student, find the student in the table and based on
the date of birth calculate and display the student’s age.

Short Answer:
Query student by name, fetch DOB, compute age using current date minus DOB in Java.

Detailed Answer:
Query: SELECT dob FROM students WHERE name = ?; parse dob using [Link], compute age with
[Link]().getYear() - [Link]().getYear() or using [Link] for exact
years/months.

---

58. State and explain any two exception classes related to JDBC?

Short Answer:
SQLException and SQLTimeoutException (subclass) — SQLException for DB errors, SQLTimeoutException
for timeout-specific issues.

Detailed Answer:
SQLException: generic DB error; SQLTimeoutException: indicates timeout in query/connection; both are
unchecked? Actually SQLException is checked, SQLTimeoutException extends SQLTransientException.

---

59. Explain with an example how to create and use Prepared Statement.

Short Answer:
PreparedStatement precompiles SQL with ? placeholders, set parameters, then
executeQuery/executeUpdate for safer and faster queries.

Detailed Answer:
PreparedStatement ps = [Link]("INSERT INTO student(name,age) VALUES(?,?)");
[Link](1,name); [Link](2,age); [Link]();

---

60. How are SQL joins executed using JDBC?

Short Answer:
Write JOIN in SQL (e.g., SELECT * FROM A JOIN B ON ...), execute via Statement/PreparedStatement and
process ResultSet.

Detailed Answer:
Write JOIN SQL (INNER/LEFT/RIGHT) in PreparedStatement: SELECT a.*, b.* FROM A INNER JOIN B ON
[Link]=[Link] WHERE [Link]=?; set parameters and process ResultSet columns using aliasing to avoid name
clashes.

---

61. Explain how a Stored Procedure can be called from JDBC.

Short Answer:
Use CallableStatement: {call procName(?,?)}; register OUT parameters and set IN parameters.

Detailed Answer:
CallableStatement cs = [Link]("{call procName(?,?)}"); [Link](1, val);
[Link](2, [Link]); [Link](); int out = [Link](2);

---

62. Write a short note on Life Cycle of a Thread?

Short Answer:
New → Runnable → Running → Waiting/Blocked/Timed_Waiting → Terminated; managed by JVM scheduler.

Detailed Answer:
See earlier 'Life Cycle' answer. Add notes on how blocked/waiting differs and how synchronization
affects transitions.

---
63. Explain with an example how a Thread can be created using Runnable Class.

Short Answer:
Implement Runnable, override run(), create Thread t = new Thread(new MyRunnable()), [Link]().

Detailed Answer:
Implement Runnable:
class MyRunnable implements Runnable { public void run(){ [Link]("Running"); } }
Thread t = new Thread(new MyRunnable()); [Link]();

---

64. State and explain the methods used for Thread Synchronization?

Short Answer:
synchronized keyword (methods/blocks), wait()/notify()/notifyAll(), Locks from
[Link].

Detailed Answer:
synchronized methods/blocks prevent concurrent access; [Link]()/notify()/notifyAll() used to
coordinate threads; [Link] provides Lock, ReentrantLock, Semaphore and higher-level
constructs for safer concurrency.

---

65. Explain with an example how Thread can be created using Thread Class.

Short Answer:
Extend Thread, override run(), create instance and call start() to run in new thread.

Detailed Answer:
Extending Thread:
class MyThread extends Thread { public void run(){ ... } }
MyThread t = new MyThread(); [Link](); // calls run in new thread
Avoid extending Thread if you also need to extend other classes; prefer Runnable.

---

You might also like