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

deepseek

The document outlines the main principles of Object-Oriented Programming (OOP) including encapsulation, inheritance, polymorphism, and abstraction, with examples in Java. It also compares procedural and object-oriented programming, discusses variable types in Java, and explains the significance of wrapper classes. Additionally, it covers Java Server Pages (JSP), including its lifecycle, scripting elements, implicit objects, and the use of tags like <jsp:forward>.

Uploaded by

lopezloyla
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)
6 views

deepseek

The document outlines the main principles of Object-Oriented Programming (OOP) including encapsulation, inheritance, polymorphism, and abstraction, with examples in Java. It also compares procedural and object-oriented programming, discusses variable types in Java, and explains the significance of wrapper classes. Additionally, it covers Java Server Pages (JSP), including its lifecycle, scripting elements, implicit objects, and the use of tags like <jsp:forward>.

Uploaded by

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

1. List the main principles of Object-Oriented Programming with examples.

The four main principles of OOP are:


1. Encapsulation:
 Encapsulation is the process of bundling data (attributes) and methods (functions)
that operate on the data into a single unit, called a class.
 It also restricts direct access to some of an object's components, which is achieved
using access modifiers like private, public, and protected.

 Example:
java
Copy
class Employee {
private String name; // Private attribute
public void setName(String name) { // Public method to set the name
this.name = name;
}
public String getName() { // Public method to get the name
return name;
}
}

2. Inheritance:
 Inheritance allows a class (subclass) to inherit attributes and methods from another
class (superclass). It promotes code reusability.
 Example:
java
Copy
class Animal { // Superclass
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal { // Subclass inheriting from Animal
void bark() {
System.out.println("The dog barks.");
}
}

3. Polymorphism:
 Polymorphism allows objects of different classes to be treated as objects of a
common superclass. It can be achieved through method overriding (runtime
polymorphism) and method overloading (compile-time polymorphism).
 Example:
java
Copy
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() { // Method overriding
System.out.println("Dog barks");
}
}

4. Abstraction:
 Abstraction is the concept of hiding complex implementation details and showing
only the necessary features of an object. It is achieved using abstract classes and
interfaces.
 Example:
java
Copy
abstract class Shape { // Abstract class
abstract void draw(); // Abstract method
}
class Circle extends Shape {
void draw() { // Implementation of abstract method
System.out.println("Drawing a circle");
}
}

2. What is the difference between procedural and object-oriented programming?


Aspect Procedural Programming Object-Oriented Programming (OOP)
Focuses on procedures or functions Focuses on objects that contain both data and
Approach
to perform tasks. methods to manipulate the data.
Data and Data and functions are encapsulated together
Data and functions are separate.
Functions in objects.
Limited reusability as functions are High reusability through inheritance and
Reusability
often specific to a task. polymorphism.
Less secure as data is exposed More secure due to encapsulation and access
Security
globally. modifiers.
Example C, Pascal Java, C++

3. What are the different types of variables in Java with examples?


In Java, variables are classified into three types:
1. Local Variables:
 Declared inside a method or block.
 Must be initialized before use.
 Example:
java
Copy
void method() {
int x = 10; // Local variable
System.out.println(x);
}

2. Instance Variables:
 Declared inside a class but outside any method.
 Belong to an instance of the class.
 Example:
java
Copy
class Employee {
String name; // Instance variable
}

3. Static Variables:

 Declared with the static keyword.

 Shared among all instances of the class.


 Example:
java
Copy
class Employee {
static String company = "ABC Corp"; // Static variable
}

4. List the significance of wrapper classes in Java with examples.


Wrapper classes in Java are used to convert primitive data types into objects. They are part of the
java.lang package and are useful in scenarios where objects are required, such as in collections.

 Significance:
1. Allow primitive types to be used in collections like ArrayList, HashMap, etc.
2. Provide utility methods for converting between primitives and strings.
3. Enable null values for primitives.
 Example:
java
Copy
int num = 10;
Integer wrappedNum = Integer.valueOf(num); // Wrapping primitive to object
int unwrappedNum = wrappedNum.intValue(); // Unwrapping object to primitive

5. How are classes and objects related in Java? Provide a simple code.
 A class is a blueprint or template for creating objects. It defines the properties (attributes)
and behaviors (methods) that the objects of the class will have.

 An object is an instance of a class. It is created using the new keyword.

 Example:
java
Copy
class Car { // Class
String color; // Attribute
void drive() { // Method
System.out.println("Car is driving");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Object of Car class
myCar.color = "Red";
myCar.drive(); // Calling method
}
}

6. Describe the process of creating and using objects in Java.


1. Define a Class:
 Create a class with attributes and methods.
 Example:
java
Copy
class Student {
String name;
int age;
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

2. Create an Object:

 Use the new keyword to create an object.

 Example:
java
Copy
Student student1 = new Student();
3. Access Attributes and Methods:

 Use the dot (.) operator to access attributes and methods.

 Example:
java
Copy
student1.name = "John";
student1.age = 20;
student1.display();

7. What is abstraction in Java? How is it achieved using abstract classes?


 Abstraction is the process of hiding complex implementation details and showing only the
essential features of an object.
 It is achieved using abstract classes and interfaces.
 Abstract Class:

 A class declared with the abstract keyword.

 It can have both abstract (no implementation) and concrete (with implementation)
methods.
 Example:
java
Copy
abstract class Animal {
abstract void sound(); // Abstract method
void sleep() { // Concrete method
System.out.println("Animal is sleeping");
}
}
class Dog extends Animal {
void sound() { // Implementation of abstract method
System.out.println("Dog barks");
}
}

8. How is abstraction different from encapsulation?


Aspect Abstraction Encapsulation
Hides complex implementation details Bundles data and methods into a single
Definition
and shows only essential features. unit and restricts access to the data.
Focuses on internal representation and
Focus Focuses on the external view of an object.
protection of data.
Achieved Access modifiers (private, public,
Abstract classes and interfaces.
by protected).
Example Abstract class Shape with abstract Private variable name with public getter
Aspect Abstraction Encapsulation
method draw(). and setter methods.

9. Show encapsulation with a code example.


Encapsulation is achieved by making fields private and providing public methods to access and
modify them.
 Example:
java
Copy
class Employee {
private String name; // Private attribute
public String getName() { // Public getter
return name;
}
public void setName(String name) { // Public setter
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName("John"); // Setting value using setter
System.out.println(emp.getName()); // Getting value using getter
}
}

10. What is inheritance? Explain different types of inheritance with examples.


 Inheritance is a mechanism where a class (subclass) inherits attributes and methods from
another class (superclass).
 Types of Inheritance:
1. Single Inheritance:
 A subclass inherits from one superclass.
 Example:
java
Copy
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal { // Single inheritance
void bark() {
System.out.println("Dog barks");
}
}
2. Multilevel Inheritance:
 A subclass inherits from another subclass.
 Example:
java
Copy
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Puppy extends Dog { // Multilevel inheritance
void weep() {
System.out.println("Puppy weeps");
}
}

3. Hierarchical Inheritance:
 Multiple subclasses inherit from a single superclass.
 Example:
java
Copy
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Dog extends Animal { // Hierarchical inheritance
void bark() {
System.out.println("Dog barks");
}
}
class Cat extends Animal { // Hierarchical inheritance
void meow() {
System.out.println("Cat meows");
}
}

4. Multiple Inheritance (Not supported in Java):


 A class inherits from more than one superclass.
 Java does not support multiple inheritance directly but achieves it through
interfaces.
 Example:
java
Copy
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B { // Multiple inheritance using interfaces
public void methodA() {
System.out.println("Method A");
}
public void methodB() {
System.out.println("Method B");
}
}

11. How does Java support inheritance? What is the significance of the super
keyword?
 Inheritance in Java:

 Java supports inheritance using the extends keyword.

 A subclass inherits all non-private members (fields and methods) of the superclass.

 super Keyword:

 Used to refer to the immediate parent class object.


 It can be used to:
1. Call the superclass constructor.
2. Access superclass methods or fields.
 Example:
java
Copy
class Animal {
String color = "White";
}
class Dog extends Animal {
String color = "Black";
void printColor() {
System.out.println(super.color); // Accessing superclass field
}
}

12. What is polymorphism? Explain compile-time and runtime polymorphism


with examples.
 Polymorphism means "many forms." It allows objects of different classes to be treated as
objects of a common superclass.
 Types of Polymorphism:
1. Compile-Time Polymorphism (Method Overloading):
 Occurs when multiple methods have the same name but different parameters.
 Resolved at compile time.
 Example:
java
Copy
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) { // Method overloading
return a + b;
}
}

2. Runtime Polymorphism (Method Overriding):


 Occurs when a subclass provides a specific implementation of a method
already defined in its superclass.
 Resolved at runtime.
 Example:
java
Copy
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() { // Method overriding
System.out.println("Dog barks");
}
}

Module 2

13. Demonstrate Java Server Pages (JSP) engine, and how does it work?
 JSP Engine:
 A JSP engine is a part of the web server that processes JSP pages. It converts JSP
code into servlets, which are then executed by the servlet engine.
 Popular JSP engines include Apache Tomcat and Jetty.
 How JSP Engine Works:
 Translation Phase:
 The JSP engine translates the JSP file into a Java servlet.

 For example, index.jsp is converted into index_jsp.java.

 Compilation Phase:

 The generated servlet is compiled into a .class file.

 Execution Phase:
 The servlet is executed, and the output (HTML) is sent to the client's browser.
 Example:
jsp
Copy
<html>
<body>
<% out.println("Hello, World!"); %>
</body>
</html>

 The JSP engine converts the above code into a servlet that generates HTML with
"Hello, World!".

14. Explain the lifecycle of a Java Server Pages (JSP). At what stage is the JSP
translated into a servlet?
The JSP lifecycle consists of the following phases:
1. Translation Phase:
 The JSP engine translates the JSP file into a Java servlet.
 This happens only once when the JSP is first requested or when it is modified.
2. Compilation Phase:

 The generated servlet is compiled into a .class file.


3. Initialization Phase:

 The jspInit() method is called to initialize the servlet.


4. Execution Phase:

 The _jspService() method is called to handle client requests.

 This method generates the dynamic content and sends it to the client.
5. Destruction Phase:

 The jspDestroy() method is called when the JSP is removed from service.

 Translation into Servlet:


 The JSP is translated into a servlet during the Translation Phase.
15. Compare between the translation and compilation phases of a Java Server
Pages (JSP) lifecycle.
Aspect Translation Phase Compilation Phase
Compiles the generated servlet into
Purpose Converts JSP code into a Java servlet.
bytecode (.class file).
When it Occurs when the JSP is first requested or Occurs immediately after the translation
Occurs when it is modified. phase.
Output Generates a .java file (servlet). Generates a .class file (bytecode).
Happens only once (unless the JSP is
Frequency Happens every time the JSP is translated.
modified).

16. Outline the role of scripting elements in Java Server Pages (JSP)? Provide
examples of declaration, scriptlet, and expression tags.
 Scripting Elements:
 Used to embed Java code in JSP pages.
 There are three types of scripting elements:
1. Declaration Tag (<%! %>):

 Used to declare variables or methods.


 Example:
jsp
Copy
<%! int count = 0; %>

2. Scriptlet Tag (<% %>):

 Used to write Java code that will be executed when the JSP is requested.
 Example:
jsp
Copy
<%
String name = request.getParameter("name");
out.println("Hello, " + name);
%>

3. Expression Tag (<%= %>):

 Used to output the result of a Java expression directly into the HTML.
 Example:
jsp
Copy
<p>Current time: <%= new java.util.Date() %></p>

17. Explain the difference between <%@ include %> and <jsp:include>.
When would you use each?
Aspect <%@ include %> <jsp:include>
Type Directive Action
When Processed during the translation phase Processed during the execution phase (at
Processed (at compile time). runtime).
Includes the content of the file
Content Includes the content of the file statically.
dynamically.
Used for static content like headers, Used for dynamic content that may
Use Case
footers, or common code. change based on conditions.
<%@ include <jsp:include
Example file="header.jsp" %> page="header.jsp" />

18. Show how can the <jsp:forward> tag be used in a Java Server Pages
(JSP)? Illustrate with an example.
 The <jsp:forward> tag is used to forward the request to another JSP or servlet.

 Example:
jsp
Copy
<jsp:forward page="welcome.jsp" />

 In this example, the request is forwarded to welcome.jsp.

19. Demonstrate any five implicit objects in Java Server Pages (JSP). Provide an
example of how the session and out objects are used.
 Implicit Objects:
 These are predefined objects available in JSP without explicit declaration.
1. request:

 Represents the HTTP request.


 Example:
jsp
Copy
String name = request.getParameter("name");

2. response:

 Represents the HTTP response.


 Example:
jsp
Copy
response.sendRedirect("welcome.jsp");

3. session:

 Represents the user session.


 Example:
jsp
Copy
session.setAttribute("username", "John");
String username = (String) session.getAttribute("username");

4. out:

 Used to write output to the client.


 Example:
jsp
Copy
out.println("Hello, World!");

5. application:

 Represents the application context.


 Example:
jsp
Copy
application.setAttribute("counter", 0);
int counter = (Integer) application.getAttribute("counter");

20. Illustrate how the request object in Java Server Pages (JSP) can be used to
retrieve form data submitted via a POST method.
 Example:
jsp
Copy
<form action="process.jsp" method="post">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>

 In process.jsp:
jsp
Copy
<%
String name = request.getParameter("name");
out.println("Hello, " + name);
%>

21. Interpret the steps involved in handling uncaught exceptions in Java Server
Pages (JSP) using error pages? Provide code examples.
1. Define an Error Page:

 Create a JSP page to handle errors (e.g., error.jsp).

 Example:
jsp
Copy
<%@ page isErrorPage="true" %>
<html>
<body>
<h1>Error Occurred</h1>
<p><%= exception.getMessage() %></p>
</body>
</html>

2. Specify the Error Page in JSP:

 Use the errorPage attribute to specify the error page.

 Example:
jsp
Copy
<%@ page errorPage="error.jsp" %>
<%
int x = 10 / 0; // This will cause an exception
%>

22. Explain the role of the "isErrorPage" attribute in Java Server Pages (JSP)
error handling. How does it enable exception access?
 isErrorPage Attribute:

 When set to true, it indicates that the JSP page is an error page.

 It enables access to the exception implicit object, which holds the exception that
caused the error.
 Example:
jsp
Copy
<%@ page isErrorPage="true" %>
<html>
<body>
<h1>Error Occurred</h1>
<p><%= exception.getMessage() %></p>
</body>
</html>

23. Show the purpose of the <c:forEach> tag in JavaServer Pages Standard
Tag Library (JSTL). How does it simplify iteration in Java Server Pages (JSP)?
 <c:forEach> Tag:

 Used to iterate over collections (e.g., lists, arrays) in JSP.


 Simplifies iteration by eliminating the need for scriptlets.
 Example:
jsp
Copy
<c:forEach var="item" items="${itemsList}">
<p>${item}</p>
</c:forEach>

24. Contrast Java Server Pages (JSP) snippet that uses JavaServer Pages
Standard Tag Library (JSTL) tags to display a list of user names from a
collection.
 Without JSTL:
jsp
Copy
<%
List<String> userNames = (List<String>) request.getAttribute("userNames");
for (String name : userNames) {
out.println("<p>" + name + "</p>");
}
%>

 With JSTL:
jsp
Copy
<c:forEach var="name" items="${userNames}">
<p>${name}</p>
</c:forEach>

 Advantage of JSTL:
 Cleaner and more readable code.
 No need for scriptlets.
Module 3

25. Explain Java Database Connectivity (JDBC), and how does it facilitate the
interaction between Java applications and databases?
 JDBC (Java Database Connectivity):
 JDBC is a Java API that enables Java applications to interact with databases.
 It provides a standard interface for connecting to relational databases, executing SQL
queries, and processing results.
 How JDBC Facilitates Interaction:
 Establish Connection:
 JDBC allows Java applications to connect to databases using a URL,
username, and password.
 Execute Queries:

 JDBC provides methods to execute SQL queries (e.g., SELECT, INSERT,


UPDATE, DELETE).

 Process Results:
 JDBC retrieves and processes the results of SQL queries using the
ResultSet object.

 Handle Transactions:
 JDBC supports transaction management to ensure data integrity.
 Example:
java
Copy
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",
"password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
while (rs.next()) {
System.out.println(rs.getString("name"));
}

26. Outline the key components of Java Database Connectivity (JDBC).


The key components of JDBC are:
1. DriverManager:
 Manages database drivers and establishes connections to databases.
2. Connection:
 Represents a connection to a specific database.
3. Statement:
 Used to execute SQL queries and updates.
4. ResultSet:
 Holds the results of a SQL query.
5. SQLException:
 Handles errors related to database access.

27. Explain the architecture of Java Database Connectivity (JDBC), detailing the
roles of the application layer, JDBC driver manager, JDBC drivers, and the
database layer.
 JDBC Architecture:
1. Application Layer:
 The Java application that uses JDBC API to interact with the database.
2. JDBC Driver Manager:
 Manages the list of database drivers and connects the application to the
appropriate driver.
3. JDBC Drivers:
 Translate JDBC API calls into database-specific calls.
 There are four types of JDBC drivers (Type 1 to Type 4).
4. Database Layer:
 The actual database (e.g., MySQL, Oracle) that stores and manages data.
 Flow:
1. Application → JDBC API → DriverManager → JDBC Driver → Database.

28. Compare the four types of Java Database Connectivity (JDBC) drivers.
Which one is most commonly used today and why?
Type Name Description Pros Cons
Uses ODBC (Open
Type JDBC-ODBC
Database Connectivity) to Easy to set up. Slow and deprecated.
1 Bridge
connect to the database.
Type Name Description Pros Cons
Type Native-API Uses database-specific
Faster than Type 1. Platform-dependent.
2 Driver native libraries.
Uses middleware to
Type Network
translate JDBC calls into Platform-independent. Requires middleware.
3 Protocol Driver
database-specific calls.
Directly converts JDBC
Type Fast and platform- Requires database-
Thin Driver calls into database-
4 independent. specific driver.
specific calls.
 Most Commonly Used:
 Type 4 (Thin Driver) is the most commonly used today because it is fast, platform-
independent, and does not require any additional software.

29. Illustrate the steps involved in connecting a Java program to a database


using Java Database Connectivity (JDBC)? Provide an example code for each
step.
1. Load the JDBC Driver:

 Load the database-specific driver using Class.forName().

 Example:
java
Copy
Class.forName("com.mysql.cj.jdbc.Driver");

2. Establish Connection:

 Use DriverManager.getConnection() to connect to the database.

 Example:
java
Copy
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",
"password");

3. Create Statement:

 Create a Statement object to execute SQL queries.

 Example:
java
Copy
Statement stmt = conn.createStatement();

4. Execute Query:
 Execute SQL queries using executeQuery() or executeUpdate().

 Example:
java
Copy
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

5. Process Results:

 Process the results using the ResultSet object.

 Example:
java
Copy
while (rs.next()) {
System.out.println(rs.getString("name"));
}

6. Close Connection:
 Close the connection to release resources.
 Example:
java
Copy
conn.close();

30. Demonstrate the role and common methods of the ResultSet object in Java
Database Connectivity (JDBC). How is it used to retrieve data from a database?
 Role of ResultSet:

 The ResultSet object holds the data returned by a SQL query.

 It acts as an iterator to traverse through the rows of the result.


 Common Methods:

 next():

 Moves the cursor to the next row.


 Example:
java
Copy
while (rs.next()) {
// Process each row
}
 getString():

 Retrieves the value of a column as a String.

 Example:
java
Copy
String name = rs.getString("name");

 getInt():

 Retrieves the value of a column as an int.

 Example:
java
Copy
int age = rs.getInt("age");

 getDouble():

 Retrieves the value of a column as a double.

 Example:
java
Copy
double salary = rs.getDouble("salary");

31. Interpret the different types of Java Database Connectivity (JDBC)


statements? Provide examples of when each type should be used.
1. Statement:
 Used for executing simple SQL queries without parameters.
 Example:
java
Copy
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

2. PreparedStatement:
 Used for executing parameterized SQL queries.
 Example:
java
Copy
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM employees WHERE
id = ?");
pstmt.setInt(1, 101);
ResultSet rs = pstmt.executeQuery();

3. CallableStatement:
 Used for executing stored procedures.
 Example:
java
Copy
CallableStatement cstmt = conn.prepareCall("{call getEmployee(?, ?)}");
cstmt.setInt(1, 101);
cstmt.registerOutParameter(2, Types.VARCHAR);
cstmt.execute();
String name = cstmt.getString(2);

32. Show how can transactions be handled in Java Database Connectivity


(JDBC) to ensure atomicity? Illustrate with an example of a transaction in
JDBC.
 Transactions in JDBC:
 Transactions ensure that a set of SQL operations are executed as a single unit
(atomicity).

 Use Connection methods like setAutoCommit(), commit(), and


rollback().

 Example:
java
Copy
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",
"password");
conn.setAutoCommit(false); // Start transaction
try {
Statement stmt = conn.createStatement();
stmt.executeUpdate("UPDATE accounts SET balance = balance - 100 WHERE id =
1");
stmt.executeUpdate("UPDATE accounts SET balance = balance + 100 WHERE id =
2");
conn.commit(); // Commit transaction
} catch (SQLException e) {
conn.rollback(); // Rollback transaction on error
} finally {
conn.setAutoCommit(true);
conn.close();
}
33. Summarize SQLException, and how is it handled in Java Database
Connectivity (JDBC)?
 SQLException:
 A checked exception that occurs during database access.
 It provides information about database errors (e.g., connection issues, SQL syntax
errors).
 Handling SQLException:

 Use try-catch blocks to handle exceptions.

 Example:
java
Copy
try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",
"password");
} catch (SQLException e) {
System.out.println("SQL Error: " + e.getMessage());
}

34. Show JDBC-ODBC Bridge driver working, and why is it deprecated?


 JDBC-ODBC Bridge:
 A Type 1 driver that uses ODBC to connect to databases.
 Example:
java
Copy
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:mydsn");

 Why Deprecated:
 It is slow and platform-dependent.
 Modern databases provide native JDBC drivers (Type 4), making the bridge obsolete.

35. Outline the purpose of the "DriverManager" class in Java Database


Connectivity (JDBC), and how does it manage database connections?
 Purpose of DriverManager:
 Manages a list of database drivers.
 Establishes connections to databases using the appropriate driver.
 How it Works:

 When DriverManager.getConnection() is called, it searches for a driver


that can handle the provided URL.
 Example:
java
Copy
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",
"password");

36. Explain the difference between java.sql and javax.sql packages. In


what scenarios would you use each?
Aspect java.sql javax.sql
Provides advanced features like
Provides basic JDBC functionality (e.g.,
Purpose connection pooling and distributed
Connection, Statement, ResultSet).
transactions.
Used in enterprise applications with
Usage Used for basic database operations.
advanced database requirements.
 Example:

 Use java.sql for simple database queries.

 Use javax.sql for connection pooling in web applications.


Module 4

37. Choose the primary difference between Swing and AWT in Java.
Aspect AWT (Abstract Window Toolkit) Swing
AWT components are heavyweight and Swing components are lightweight and
Architecture
rely on native platform-specific code. written entirely in Java.
Faster and more efficient as it is
Performance Slower due to reliance on native code.
platform-independent.
Limited to the look and feel of the native Supports pluggable look and feel (e.g.,
Look and Feel
platform. Windows, Metal, Nimbus).
Highly customizable with rich set of
Customization Limited customization options.
components.
JButton in Swing is a Java-based
Example Button in AWT is a native button.
button.

38. Identify the three features of Java Swing and explain how they contribute to
the development of platform-independent Graphical User Interface (GUI)
applications.
1. Lightweight Components:
 Swing components are written entirely in Java, making them platform-independent.
 Contribution: Ensures consistent behavior and appearance across different operating
systems.
2. Pluggable Look and Feel:
 Swing allows developers to change the appearance of the GUI using different look
and feel themes.
 Contribution: Provides flexibility to match the application's look and feel with the
user's preferences or platform standards.
3. Rich Set of Components:

 Swing provides a wide range of components (e.g., JTable, JTree,


JFileChooser) for building complex GUIs.

 Contribution: Enables developers to create feature-rich and interactive applications.

39. Make use of the Model-View-Controller (MVC) architecture as it applies to


Swing components? Provide an example.
 MVC Architecture:
 Model: Represents the data and business logic.
 View: Represents the UI components.
 Controller: Handles user input and updates the model.
 Example in Swing:

 Model: A DefaultTableModel for a JTable.

 View: The JTable component.

 Controller: Event listeners (e.g., ActionListener) that update the model based
on user input.
 Code Example:
java
Copy
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class MVCExample {


public static void main(String[] args) {
// Model
DefaultTableModel model = new DefaultTableModel(new Object[]{"Name",
"Age"}, 0);

// View
JTable table = new JTable(model);
JFrame frame = new JFrame("MVC Example");
frame.add(new JScrollPane(table));
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

// Controller
JButton addButton = new JButton("Add Row");
addButton.addActionListener(e -> {
model.addRow(new Object[]{"John", 25}); // Update model
});
frame.add(addButton, "South");
}
}

40. Choose the purpose of a JFrame in Java Swing, and how do you create one?
 Purpose of JFrame:

 JFrame is the main window for Swing applications. It provides a container for other
Swing components (e.g., buttons, labels).
 Creating a JFrame:
 Example:
java
Copy
import javax.swing.*;

public class JFrameExample {


public static void main(String[] args) {
JFrame frame = new JFrame("My JFrame");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

41. Build the function of the "FlowLayout" layout manager in Java Swing.
Provide an example where it might be useful.
 FlowLayout:
 Arranges components in a row, left to right, and wraps to the next row if necessary.
 Use Case: Useful for simple forms or toolbars where components are arranged
sequentially.
 Example:
java
Copy
import javax.swing.*;
import java.awt.FlowLayout;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setLayout(new FlowLayout());

frame.add(new JButton("Button 1"));


frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));

frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

42. Identify the differences between JDialog and JFrame in Java Swing. Provide
a use case for each.
Aspect JFrame JDialog
Used as the main window for
Purpose Used for pop-up dialogs or secondary windows.
applications.
Can be modal (blocks input to other windows) or
Modal Non-modal by default.
non-modal.
Main application window (e.g., a text
Use Case Dialog boxes (e.g., "Save As" dialog).
editor).
 Example:
java
Copy
// JFrame
JFrame frame = new JFrame("Main Window");
frame.setSize(400, 300);
frame.setVisible(true);

// JDialog
JDialog dialog = new JDialog(frame, "Dialog", true);
dialog.setSize(200, 100);
dialog.setVisible(true);

43. Construct a button click event in Java Swing with code.


 Button Click Event:

 Use ActionListener to handle button clicks.

 Example:
java
Copy
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonClickExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Click Example");
JButton button = new JButton("Click Me");

button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
});

frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

44. Choose and explain the key components of a JMenu in Java Swing, and how
would you implement a simple menu.
 Key Components of JMenu:
1. JMenuBar: Container for menus.
2. JMenu: A dropdown menu (e.g., "File").
3. JMenuItem: An item in the menu (e.g., "New", "Open").
 Example:
java
Copy
import javax.swing.*;

public class MenuExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Menu Example");
JMenuBar menuBar = new JMenuBar();

JMenu fileMenu = new JMenu("File");


JMenuItem newItem = new JMenuItem("New");
JMenuItem openItem = new JMenuItem("Open");

fileMenu.add(newItem);
fileMenu.add(openItem);
menuBar.add(fileMenu);

frame.setJMenuBar(menuBar);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
45. Build exception handling in Java Swing applications? How would you handle
a NullPointerException in a Swing app?
 Exception Handling in Swing:

 Use try-catch blocks to handle exceptions.

 Display error messages using JOptionPane.

 Example:
java
Copy
import javax.swing.*;

public class ExceptionHandlingExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Exception Handling Example");
JButton button = new JButton("Cause Exception");

button.addActionListener(e -> {
try {
String str = null;
str.length(); // This will cause a NullPointerException
} catch (NullPointerException ex) {
JOptionPane.showMessageDialog(frame, "Error: " +
ex.getMessage());
}
});

frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

46. Identify the advantages of using NetBeans and Eclipse for Swing
development. Which Integrated Development Environment (IDE) would you
choose for a simple Graphical User Interface (GUI) application and why?
Aspect NetBeans Eclipse
Requires plugins (e.g.,
Swing Excellent built-in support for Swing with a
WindowBuilder) for Swing
Support drag-and-drop GUI builder.
development.
Steeper learning curve but highly
Ease of Use Beginner-friendly with intuitive tools.
customizable.
Larger community and more plugins
Community Strong community support.
available.
 Recommendation:
 For a simple GUI application, NetBeans is recommended due to its built-in Swing
support and ease of use.
47. Make use of the function "JPanel" container in Swing. Provide an example
scenario where it is used.
 JPanel:
 A lightweight container used to group components together.
 Example Scenario:
 Grouping buttons in a toolbar.
 Example:
java
Copy
import javax.swing.*;

public class JPanelExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JPanel Example");
JPanel panel = new JPanel();

panel.add(new JButton("Button 1"));


panel.add(new JButton("Button 2"));

frame.add(panel);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

48. Develop how the "BoxLayout" layout manager works in Java Swing.
 BoxLayout:
 Arranges components either vertically or horizontally in a single row or column.
 Use Case: Useful for creating toolbars or vertical/horizontal stacks of components.
 Example:
java
Copy
import javax.swing.*;
import java.awt.BoxLayout;

public class BoxLayoutExample {


public static void main(String[] args) {
JFrame frame = new JFrame("BoxLayout Example");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // Vertical
arrangement

panel.add(new JButton("Button 1"));


panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
frame.add(panel);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Module 5:

49. Build and explain the mapping in Hibernate.


 Hibernate Mapping:
 Hibernate is an ORM (Object-Relational Mapping) framework that maps Java
objects to database tables and vice versa.
 It eliminates the need for writing SQL queries manually by providing a high-level
API for database operations.
 Mapping Types:
 Class to Table Mapping:
 A Java class is mapped to a database table.
 Example:
java
Copy
@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
// Getters and setters
}

 Property to Column Mapping:


 Fields in the class are mapped to columns in the table.
 Example:
java
Copy
@Column(name = "emp_name")
private String name;

50. Identify the annotation used in Hibernate to represent a one-to-one


relationship between two entities.
 Annotation for One-to-One Relationship:
 @OneToOne is used to define a one-to-one relationship between two entities.

 Example:
java
Copy
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@OneToOne
@JoinColumn(name = "address_id")
private Address address;
// Getters and setters
}

@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String city;
// Getters and setters
}

51. Identify the annotation in Hibernate used to represent a many-to-one


relationship.
 Annotation for Many-to-One Relationship:

 @ManyToOne is used to define a many-to-one relationship between two entities.

 Example:
java
Copy
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Getters and setters
}

@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
// Getters and setters
}

52. Select the difference between one-to-one and many-to-one mapping in


Hibernate.
Aspect One-to-One Mapping Many-to-One Mapping
One entity is associated with exactly one Many entities are associated with one
Relationship
instance of another entity. instance of another entity.
Annotation @OneToOne @ManyToOne
Many employees belong to one
Example One employee has one address.
department.

53. Identify the role of @JoinColumn in Hibernate's one-to-one and many-to-


one mappings.
 Role of @JoinColumn:

 @JoinColumn specifies the foreign key column in the database table.

 It is used in conjunction with @OneToOne or @ManyToOne to define the


relationship.
 Example:
java
Copy
@OneToOne
@JoinColumn(name = "address_id") // Foreign key column in the Employee table
private Address address;

54. Choose how the mappedBy attribute is used in Hibernate's one-to-many


mapping.
 mappedBy Attribute:

 Used in bidirectional relationships to indicate that the relationship is owned by the


other entity.
 It is placed on the non-owning side of the relationship.
 Example:
java
Copy
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@OneToMany(mappedBy = "department") // Owned by Employee


private List<Employee> employees;
// Getters and setters
}

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id") // Owning side
private Department department;
// Getters and setters
}

55. Construct the Hibernate annotation code for a many-to-many relationship


between Student and Course.
 Many-to-Many Relationship:

 Use @ManyToMany and @JoinTable to define the relationship.

 Example:
java
Copy
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@ManyToMany
@JoinTable(
name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id")
)
private List<Course> courses;
// Getters and setters
}

@Entity
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@ManyToMany(mappedBy = "courses") // Owned by Student


private List<Student> students;
// Getters and setters
}
56. Experiment with the given scenario where an employee works for one
department but multiple employees work for the same department. Create the
necessary Hibernate annotations.
 Scenario:
 Many employees belong to one department.
 Annotations:
java
Copy
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Getters and setters
}

@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@OneToMany(mappedBy = "department")
private List<Employee> employees;
// Getters and setters
}

57. Build a simple Hibernate mapping for a one-to-one relationship between


Author and Book, where each author can have only one book.
 One-to-One Relationship:
java
Copy
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@OneToOne(mappedBy = "author")
private Book book;
// Getters and setters
}
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String title;

@OneToOne
@JoinColumn(name = "author_id")
private Author author;
// Getters and setters
}

58. Identify and compare the @OneToMany and @ManyToMany annotations in


terms of their usage in Hibernate.
Aspect @OneToMany @ManyToMany
One entity is associated with many Many entities are associated with many
Relationship
instances of another entity. instances of another entity.
Owning side is the "many" side (e.g., Owning side is defined using
Owning Side
@ManyToOne). @JoinTable.
Example One department has many employees. Many students enroll in many courses.

59. Apply the correct mapping approach, given the entity classes Product and
Category, where each product can belong to multiple categories, and each
category can have multiple products.
 Many-to-Many Relationship:
java
Copy
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@ManyToMany
@JoinTable(
name = "product_category",
joinColumns = @JoinColumn(name = "product_id"),
inverseJoinColumns = @JoinColumn(name = "category_id")
)
private List<Category> categories;
// Getters and setters
}

@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
@ManyToMany(mappedBy = "categories") // Owned by Product
private List<Product> products;
// Getters and setters
}

60. Develop and build the model using Hibernate annotation, if a department
can have many employees but an employee can only belong to one department.
 One-to-Many Relationship:
java
Copy
@Entity
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@OneToMany(mappedBy = "department")
private List<Employee> employees;
// Getters and setters
}

@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
// Getters and setters
}

You might also like