Screenshot 2024-11-24 at 8.42.48 PM
Screenshot 2024-11-24 at 8.42.48 PM
[5×1=5]
1. FlowLayout
2. BorderLayout
3. GridLayout
The JVM has a garbage collector that continuously monitors for objects that are unreachable (no longer
referenced) and removes them from memory. Java does not require explicit deletion of objects, as in some
other languages like C++. Instead, once an object becomes unreachable, it becomes eligible for garbage
collection.
Example:
java
Copy code
public class GarbageCollectionExample {
public static void main(String[] args) {
String str = new String("Hello");
str = null; // The "Hello" object is now eligible for garbage collection
System.gc(); // Requesting JVM for garbage collection (not guaranteed)
}
}
Answer:
In Java, an interface is a reference type that defines a set of abstract methods that classes can implement.
Interfaces are used to specify a contract that implementing classes must follow, promoting multiple
inheritance and polymorphism.
To define an interface, use the interface keyword. A class that implements an interface must provide
concrete implementations for all of its methods.
Example:
java
Copy code
// Defining an interface
interface Animal {
void sound();
void eat();
}
Answer:
MVC (Model-View-Controller) is a design pattern used to separate an application into three main
components:
1. Model: Manages the data and business logic of the application. It does not interact directly with the
user.
2. View: Handles the display of information (UI) to the user.
3. Controller: Acts as an intermediary between Model and View, taking input from the user (through
the View), updating the Model, and refreshing the View accordingly.
The MVC architecture promotes a clear separation of concerns, making applications easier to manage and
scale.
java
Copy code
// Model
class CounterModel {
private int count = 0;
// View
class CounterView {
public void displayCount(int count) {
System.out.println("Current count: " + count);
}
}
// Controller
class CounterController {
private CounterModel model;
private CounterView view;
d) Define:
• i) TYPE_FORWARD_ONLY
Answer: This type of result set is non-scrollable, meaning the cursor can only move forward, one
row at a time. Once moved past a row, you cannot return to it.
• ii) TYPE_SCROLL_INSENSITIVE
Answer: This result set type allows the cursor to move both forward and backward, and it is not
affected by changes made to the database while the result set is open. This means that even if the
underlying data changes, the result set data remains unchanged.
• iii) CONCUR_UPDATABLE
Answer: This concurrency type allows updates to the result set. This means that you can make
changes to the database through the result set, which will then be reflected in the database.
e) What is scripting elements? Explain any two types.
Answer:
Scripting elements in JSP (JavaServer Pages) are used to add Java code within an HTML page. They allow
dynamic content generation and are essential for implementing logic within JSP pages. There are three types
of scripting elements: declarations, scriptlets, and expressions.
1. Scriptlets (<% ... %>): Scriptlets allow you to embed Java code directly into a JSP file. This code is
executed every time the page is requested. Example:
jsp
Copy code
<%
String greeting = "Hello, World!";
out.println(greeting);
%>
2. Expressions (<%= ... %>): Expressions evaluate a Java expression and print the result to the
response stream. The result is automatically converted to a string and inserted into the output.
Example:
jsp
Copy code
<%= "Today is: " + new java.util.Date() %>
Answer:
Example:
java
Copy code
// String (immutable)
String str = "Hello";
str = str + " World"; // Creates a new String object
// StringBuffer (mutable)
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // Modifies the same StringBuffer object
System.out.println(sb.toString()); // Output: Hello World
Q3) Answer the following with example in brief. (Any five) [5×4=20]
Example:
jsp
Copy code
<%@ page language="java" %>
<html>
<body>
<h1>Welcome to JSP Life Cycle</h1>
</body>
</html>
Answer:
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones,
starting from 0 and 1.
Example Program:
java
Copy code
public class FibonacciSeries {
public static void main(String[] args) {
int n = 10, num1 = 0, num2 = 1;
System.out.print("Fibonacci Series: " + num1 + ", " + num2);
Answer:
There are four types of JDBC drivers:
Answer:
To create a package, use the package keyword. Classes in the package can then be accessed using the
import statement.
Example:
java
Copy code
// File: MyPackage/MyClass.java
package MyPackage;
java
Copy code
import MyPackage.MyClass;
Answer:
Example:
java
Copy code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
// Using Scanner
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int number = sc.nextInt();
System.out.println("You entered: " + number);
sc.close();
}
}
Answer:
The factorial of a number n is the product of all positive integers less than or equal to n.
Example Program:
java
Copy code
import java.util.Scanner;
Answer:
A simple Java Swing program that creates a frame with radio buttons for "Male," "Female," "Yes," and
"No," and displays the selected option.
Example Program:
java
Copy code
import javax.swing.*;
import java.awt.event.*;
frame.add(panel);
frame.setVisible(true);
}
}
Q4) Answer the following in brief with example (Any five) [5×5=25]
a) Write a Java program that accepts a number using a command line argument and displays
whether the number is perfect or not.
A perfect number is a number that is equal to the sum of its proper divisors (excluding itself). For example,
6 is a perfect number because 1 + 2 + 3 = 6.
Example Program:
java
Copy code
public class PerfectNumber {
public static void main(String[] args) {
if (args.length > 0) {
int number = Integer.parseInt(args[0]);
int sum = 0;
if (sum == number) {
System.out.println(number + " is a perfect number.");
} else {
System.out.println(number + " is not a perfect number.");
}
} else {
System.out.println("Please enter a number as a command line argument.");
}
}
}
Usage: Run the program with a command line argument, e.g., java PerfectNumber 6
Answer:
Java provides four access specifiers to control the visibility and accessibility of classes, methods, and
variables.
java
Copy code
public class PublicExample {
public void display() {
System.out.println("This is a public method.");
}
}
java
Copy code
class ProtectedExample {
protected void display() {
System.out.println("This is a protected method.");
}
}
java
Copy code
class DefaultExample {
void display() {
System.out.println("This is a default method.");
}
}
java
Copy code
class PrivateExample {
private void display() {
System.out.println("This is a private method.");
}
}
Answer:
Method overriding is when a subclass provides a specific implementation of a method already defined in its
superclass. Runtime polymorphism is achieved through method overriding, where the overridden method
that is called is determined at runtime.
Example:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
In this example, the sound method of Dog class is called at runtime due to polymorphism.
d) Define:
1. TreeSet: A sorted set that stores elements in ascending order, unique and without duplicates.
java
Copy code
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("Apple");
treeSet.add("Banana");
2. HashMap: A collection that stores key-value pairs, does not maintain order, and allows null values.
java
Copy code
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
java
Copy code
TreeMap<Integer, String> treeMap = new TreeMap<>();
treeMap.put(2, "Two");
treeMap.put(1, "One");
4. ArrayList: A resizable array that allows duplicate elements and maintains insertion order.
java
Copy code
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("One");
arrayList.add("Two");
5. LinkedList: A doubly-linked list that can store duplicate elements and maintains insertion order.
java
Copy code
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("One");
linkedList.add("Two");
Answer:
Wrapper classes in Java are used to convert primitive data types into objects. They are part of the
java.lang package and include classes like Integer, Double, Character, etc. Wrapper classes are useful
when objects are required instead of primitive types.
Example:
java
Copy code
public class WrapperExample {
public static void main(String[] args) {
int primitive = 5;
Integer wrapper = Integer.valueOf(primitive); // Autoboxing
Answer:
Inheritance is an object-oriented concept where one class (child or subclass) inherits properties and
behaviors (fields and methods) from another class (parent or superclass). It allows code reuse and establishes
a parent-child relationship between classes.
Types of Inheritance:
java
Copy code
class Parent {}
class Child extends Parent {}
2. Multilevel Inheritance: A class inherits from a class that already inherits from another class.
java
Copy code
class GrandParent {}
class Parent extends GrandParent {}
class Child extends Parent {}
java
Copy code
class Parent {}
class Child1 extends Parent {}
class Child2 extends Parent {}
Note: Java does not support multiple inheritance (one class inheriting from multiple classes) to avoid
complexity.
Answer:
• Cookies: Small pieces of data stored on the client’s browser to keep track of user information across
sessions. Cookies can store user preferences, session identifiers, etc., and are sent with every request
to the server.
java
Copy code
Cookie userCookie = new Cookie("username", "John");
response.addCookie(userCookie);
• HttpSession: A session management mechanism that stores information about a user’s session on
the server side. The server creates an HttpSession object for each user, which persists throughout
the session. It’s more secure than cookies for sensitive data.
java
Copy code
HttpSession session = request.getSession();
session.setAttribute("username", "John");
String username = (String) session.getAttribute("username");
Q1) Attempt the following. [5×1=5]
• Answer: Java is called portable because Java programs can run on any platform with a compatible Java
Virtual Machine (JVM). The bytecode generated by Java is platform-independent, allowing the program to be
run on different operating systems without modification.
b) What is a superclass?
• Answer: A superclass is a class from which other classes inherit properties and methods. Inheritance in Java
allows one class (subclass) to inherit features from another class (superclass), promoting code reuse and a
hierarchical classification.
• Answer: The Collection interface in Java is the root interface of the collection framework. It provides the
standard functionality for all collections in Java, such as adding, removing, and checking the size of elements.
Common classes implementing Collection include List, Set, and Queue.
e) Define ResultSet
• Answer: ResultSet is a Java interface used to store the results of a database query executed using JDBC. It
provides methods to navigate and retrieve the data returned by the query, typically through methods like
next(), getString(), getInt(), etc. The ResultSet is usually generated by executing a SELECT
statement.
Q2) Answer the following in brief with examples (Any five) [5×3=15]
• Answer:
Static fields and methods belong to the class rather than instances of the class. They are shared
among all instances and can be accessed without creating an instance of the class.
• Static Field Example:
java
Copy code
class Example {
static int count = 0; // static field
public Example() {
count++; // increments count every time an instance is created
}
}
java
Copy code
class MathUtil {
static int square(int number) {
return number * number; // static method
}
}
java
Copy code
final int MAX_VALUE = 100;
java
Copy code
class Parent {
final void display() {
System.out.println("This is a final method.");
}
}
java
Copy code
final class Utility {
// Class code
}
• Answer:
Exception handling in Java is a mechanism to handle runtime errors so the normal flow of the
program is not disrupted. Java provides try, catch, finally, throw, and throws keywords to
handle exceptions.
• Example:
java
Copy code
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("Execution completed.");
}
}
}
o Output:
csharp
Copy code
Cannot divide by zero.
Execution completed.
• Answer:
Keyboard events in Java are used to capture and respond to key presses. KeyListener interface
provides methods to handle events like key presses, key releases, and key typing.
• Example:
java
Copy code
import java.awt.event.*;
import javax.swing.*;
mathematica
Copy code
Key Pressed: A
Key Typed: A
Key Released: A
• Answer:
In Java Database Connectivity (JDBC), Connection and Statement are used to interact with
databases, but they serve different purposes.
o Connection: This object represents a connection to the database. It is used to establish a link
with the database and manage transactions.
java
Copy code
Connection connection = DriverManager.getConnection("url", "user",
"password");
o Statement: This object is used to execute SQL queries and return results. It is created from a
Connection object.
java
Copy code
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM table_name");
o Key Difference:
▪ Connection is responsible for establishing and managing database links, while
Statement is used for executing SQL queries on the database.
• Answer:
Session tracking is a way to maintain state across multiple requests in a web application. Common
session tracking techniques in Java are cookies, URL rewriting, hidden form fields, and
HttpSession.
o Cookies: Small pieces of data stored on the client side, sent with each request to maintain
session information.
o URL Rewriting: Appends session ID to the URL to identify the client.
o Hidden Form Fields: Hidden fields in forms to store session data.
o HttpSession: Server-side storage of session information.
• Example using HttpSession:
java
Copy code
// Setting a session attribute
HttpSession session = request.getSession();
session.setAttribute("username", "JohnDoe");
o Explanation: The HttpSession object stores session data for a user across multiple requests.
When a user logs in, session attributes can be set, and these can be retrieved in future
requests.
Q3) Answer the following in brief (more detailed) with examples (Any five) [5×4=20]
• Answer:
A Servlet is a Java class used to handle requests and generate dynamic web content on a server.
Servlets are server-side programs that operate within a web server and handle client requests, such as
form submissions or database interactions.
• Types of Servlets:
o Generic Servlet: This is an abstract class provided by Java, which can be used to create any
type of servlet by extending it and implementing its service() method. It does not have
HTTP-specific methods.
java
Copy code
import javax.servlet.*;
import java.io.*;
java
Copy code
import javax.servlet.http.*;
import java.io.*;
• Answer:
JDBC (Java Database Connectivity) drivers are used to connect Java applications with a database.
There are four types of JDBC drivers:
o Type-1: JDBC-ODBC Bridge Driver
It translates JDBC calls to ODBC calls. This driver depends on the native ODBC driver and
is generally slower.
java
Copy code
Connection conn = DriverManager.getConnection("jdbc:odbc:DatabaseName",
"username", "password");
• Answer:
java
Copy code
import javax.swing.*;
import java.awt.event.*;
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(frame, e.getX(), e.getY());
}
}
});
frame.setVisible(true);
}
}
d) Write a Java program to create an abstract class Student with two derived classes Marks and
Result. Use proper methods to accept and display the data.
• Answer:
java
Copy code
abstract class Student {
String name;
int rollNumber;
void getDetails() {
// Here, assume we get data from the user
name = "John";
rollNumber = 101;
marks = 85;
}
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
}
}
void calculateResult() {
result = (marks >= 40) ? "Pass" : "Fail";
}
void displayDetails() {
super.displayDetails();
System.out.println("Result: " + result);
}
}
public class Main {
public static void main(String[] args) {
Result student = new Result();
student.getDetails();
student.calculateResult();
student.displayDetails();
}
}
• Answer:
o Public: Accessible from any class.
o Protected: Accessible within the same package and subclasses.
o Default (No Modifier): Accessible only within the same package.
o Private: Accessible only within the same class.
Example:
java
Copy code
public class Example {
public int publicVar = 10;
protected int protectedVar = 20;
int defaultVar = 30;
private int privateVar = 40;
}
• Answer:
o Checked Exceptions: These exceptions are checked at compile-time and must be handled
with try-catch or declared with throws. Examples include IOException, SQLException.
o Unchecked Exceptions: These are not checked at compile-time and can occur during
program execution. Examples include NullPointerException, ArithmeticException.
Example:
java
Copy code
// Checked Exception example
try {
FileInputStream file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
• Answer:
JSP directives are special instructions to the JSP engine that control the processing of the JSP page.
The three main types of directives are:
o Page Directive (<%@ page ... %>): Defines attributes related to the entire JSP page, such as
language, contentType, and import.
jsp
Copy code
<%@ page language="java" contentType="text/html" %>
o Include Directive (<%@ include ... %>): Inserts the contents of another file into the
current JSP file.
jsp
Copy code
<%@ include file="header.jsp" %>
o Taglib Directive (<%@ taglib ... %>): Declares a custom tag library to be used in the JSP.
jsp
Copy code
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
• Answer:
A constructor in Java is a special method used to initialize objects. It has the same name as the class
and does not have a return type. Constructors are invoked automatically when an object of a class is
created.
• Types of Constructors:
o Default Constructor: A constructor with no parameters. If no constructor is defined, Java
provides a default constructor.
java
Copy code
class Example {
Example() { // Default constructor
System.out.println("Default constructor called");
}
}
java
Copy code
class Example {
int x;
Example(int value) { // Parameterized constructor
x = value;
}
}
b) What is Inheritance? Explain any two types of inheritance with suitable examples.
• Answer:
Inheritance is a feature in object-oriented programming that allows a class to inherit fields and
methods from another class. It promotes code reuse and establishes a relationship between classes.
• Types of Inheritance:
o Single Inheritance: In this type, a class (subclass) inherits from only one superclass.
java
Copy code
class Animal {
void eat() { System.out.println("Eating..."); }
}
o Multilevel Inheritance: In this type, a class is derived from another derived class.
java
Copy code
class Animal {
void eat() { System.out.println("Eating..."); }
}
c) Explain any four methods of String class with the help of an example.
• Answer:
The String class in Java has many useful methods for string manipulation.
o length(): Returns the length of the string.
java
Copy code
String str = "Hello";
System.out.println(str.length()); // Output: 5
java
Copy code
String str = "Hello";
System.out.println(str.charAt(1)); // Output: e
java
Copy code
String str = "Hello";
System.out.println(str.substring(1, 3)); // Output: el
java
Copy code
String str = "hello";
System.out.println(str.toUpperCase()); // Output: HELLO
d) Create a table of Teacher with fields (Tid, Tname, Taddress) and write a JDBC program to insert
and display all teacher details.
• Answer:
java
Copy code
import java.sql.*;
try {
Connection conn = DriverManager.getConnection(url, user, password);
while (rs.next()) {
System.out.println("Tid: " + rs.getInt("Tid"));
System.out.println("Tname: " + rs.getString("Tname"));
System.out.println("Taddress: " + rs.getString("Taddress"));
}
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
e) Write a Servlet program that counts how many times a user has visited a web page (use session).
• Answer:
java
Copy code
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
if (visitCount == null) {
visitCount = 1;
} else {
visitCount++;
}
session.setAttribute("visitCount", visitCount);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Number of visits: " + visitCount + "</h1>");
}
}
• Answer:
An interface in Java is a reference type, similar to a class, that can contain only constants, method
signatures, default methods, and static methods. Interfaces provide a way to achieve abstraction and
multiple inheritance in Java.
• Example:
java
Copy code
interface Drawable {
void draw(); // Abstract method
}
g) Write a Java program to accept numbers in a vector and display the sum of all elements.
• Answer:
java
Copy code
import java.util.*;
int sum = 0;
for (int num : numbers) {
sum += num;
}
o Explanation: The program accepts numbers and stores them in a Vector. After all entries
are made, it calculates the sum of all elements and displays it.
• Answer: c) new
Explanation: The new operator in Java is used to allocate memory for objects.
• Answer: d) extends
iii) When an error occurs, then if checked, the exception type is in the _______ block.
• Answer: b) catch
Explanation: In Java, exceptions are handled in the catch block, where the type of exception is identified
and managed.
• Answer: b) JMenu
Explanation: The JMenu class in Swing is used to create menus in a Java GUI application.
• Answer: c) ResultSet
Explanation: In JDBC, ResultSet is an interface used to store and manage the result of a database query.
• Answer:
J2EE (Java 2 Platform, Enterprise Edition) is a platform-independent, Java-centric environment
developed by Sun Microsystems for building, developing, and deploying web-based enterprise
applications. It provides APIs and runtime environments for scripting and running Java applications,
including networking, web services, and more.
• Answer:
A JDBC Driver is a software component that enables Java applications to interact with a database. It
translates Java SQL queries into database-specific calls, allowing Java programs to perform database
operations. Examples include the JDBC-ODBC bridge driver and MySQL JDBC driver.
• Answer:
The Swing classes used to create menus in Java include:
o JMenu: Represents a menu.
o JMenuBar: Represents a menu bar to hold menus.
o JMenuItem: Represents an individual menu item.
o JCheckBoxMenuItem and JRadioButtonMenuItem: Specialized menu items.
• Answer:
True. The Vector class in Java is dynamically resizable, meaning it can grow or shrink as elements
are added or removed.
• Answer:
Common layout managers in Java Swing include:
o BorderLayout
o FlowLayout
o GridLayout
o CardLayout
o GridBagLayout
java
Copy code
// This is a single-line comment
int x = 10;
o Multi-line Comment: Starts with /* and ends with */. Used for block comments.
java
Copy code
/* This is a multi-line comment.
It spans multiple lines. */
int y = 20;
o Documentation Comment: Begins with /** and ends with */. Used to create documentation
for classes, methods, and fields. Processed by Javadoc.
java
Copy code
/**
* This method adds two numbers.
* @param a First number
* @param b Second number
* @return Sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
• Answer:
Polymorphism is the ability of an object to take on many forms. In Java, it allows methods to do
different things based on the object that it is acting upon. Runtime polymorphism (or dynamic
method dispatch) occurs when a method call to an overridden method is resolved at runtime, not at
compile time.
• Example of Runtime Polymorphism:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
• Answer:
A Map is a part of Java’s Collection Framework and is used to store key-value pairs. Unlike lists, a
Map does not allow duplicate keys.
o HashMap: A HashMap stores key-value pairs in a hash table. It does not maintain any order
of elements.
java
Copy code
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
System.out.println(ages); // Output: {Alice=25, Bob=30}
java
Copy code
Map<String, Integer> scores = new TreeMap<>();
scores.put("Alice", 88);
scores.put("Bob", 95);
System.out.println(scores); // Output: {Alice=88, Bob=95}
• Answer:
Dialogs in Java are pop-up windows that prompt the user for input or provide a message. Swing
provides classes like JOptionPane for creating dialogs easily.
• Example: Creating an input dialog using JOptionPane
java
Copy code
import javax.swing.*;
• Answer:
o Statement: In JDBC, a Statement object is used to execute SQL queries against the
database. It is mainly used for executing simple SQL statements without parameters.
java
Copy code
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Students");
java
Copy code
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM
Students WHERE id = ?");
pstmt.setInt(1, 1); // sets the id parameter
ResultSet rs = pstmt.executeQuery();
java
Copy code
CallableStatement cstmt = connection.prepareCall("{call getStudent(?)}");
cstmt.setInt(1, 1); // set the parameter for stored procedure
ResultSet rs = cstmt.executeQuery();
• Answer:
In JavaServer Pages (JSP), scripting elements allow Java code to be embedded in HTML pages.
The main types are:
o Declaration (<%! ... %>): Declares variables or methods that can be used in the JSP page.
jsp
Copy code
<%! int counter = 0; %>
o Scriptlet (<% ... %>): Contains Java code that is executed every time the page is requested.
It can contain expressions and statements.
jsp
Copy code
<% counter++; %>
o Expression (<%= ... %>): Used to output Java expressions to the client, directly embedded
in HTML.
jsp
Copy code
<h1>Counter Value: <%= counter %></h1>
Q3) Attempt the following with example (Any Five) [5 × 4 = 20]
• Answer:
Both BufferedReader and Scanner classes are used to read input in Java, but they have different
characteristics.
o BufferedReader: This class reads text from an input stream efficiently using a buffer, which
can improve performance when reading a large amount of data. It reads input line by line and
is often used with InputStreamReader to read console input.
java
Copy code
import java.io.*;
o Scanner: The Scanner class provides more flexible input parsing and supports tokenizing. It
can read different data types (e.g., int, float, String) and is generally more user-friendly
for basic input tasks.
java
Copy code
import java.util.Scanner;
b) What are the primitive data types in Java? Write about type conversion.
Type Conversion:
o Implicit (Automatic) Conversion: Java automatically converts smaller data types to larger
ones. For example, int to long.
java
Copy code
int num = 100;
long bigNum = num; // Implicit conversion from int to long
o Explicit (Manual) Conversion: Requires casting to convert a larger type to a smaller one.
For example, double to int.
java
Copy code
double decimalNum = 9.7;
int intNum = (int) decimalNum; // Explicit conversion from double to int
c) Write a Java program to check if age is greater than 18. Give appropriate message (using exception
handling).
• Answer:
java
Copy code
import java.util.Scanner;
• Answer: MVC (Model-View-Controller) is a design pattern that separates the application into three
main components:
o Model: Represents the data and business logic of the application. The model notifies the view
when the data changes.
o View: Displays the data from the model to the user and sends user actions to the controller.
o Controller: Processes user input, interacts with the model, and updates the view.
o Diagram:
sql
Copy code
+-----------+ +----------+
| | <------> | |
| Model | | View |
| | <------> | |
+-----------+ +----------+
^ ^
| |
+---------------------+
|
Controller
o Explanation: In Java, this pattern is often seen in frameworks where the controller handles
user actions, updates the model, and then refreshes the view based on the model's new state.
Example:
jsp
Copy code
<%-- JSP code starts --%>
<%@ page language="java" %>
<html>
<body>
<h1>Welcome to the JSP Life Cycle Example</h1>
<p>The current time is: <%= new java.util.Date() %></p>
</body>
</html>
• Answer: The super keyword in Java is used to refer to the immediate parent class object. It can be
used for:
o Calling the parent class constructor.
o Accessing a parent class method or variable that has been overridden.
Example:
java
Copy code
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
o Output:
Copy code
Animal sound
Dog barks
• Answer: In Java, a package is a way to group related classes and interfaces. To create a package,
use the package keyword, and then access it by importing the package.
o Creating a Package:
java
Copy code
// File: MyPackage/Example.java
package MyPackage;
o Accessing a Package:
java
Copy code
import MyPackage.Example;
o Explanation: The Example class is part of the MyPackage package. To use it in Main, we
import it with import MyPackage.Example.
• Answer:
The Servlet life cycle defines how a servlet is loaded, initialized, and destroyed in a web server
environment. The three main phases of a servlet’s life cycle are initialization, service, and
destruction.
o 1. Loading and Instantiation: When a servlet is requested for the first time, it is loaded and
instantiated by the servlet container.
o 2. Initialization (init method): The init() method is called once, allowing the servlet to
perform setup activities (e.g., initializing resources).
o 3. Service (service method): This method handles client requests and provides responses.
The service() method is called for each request.
o 4. Destruction (destroy method): When the servlet is no longer needed, the destroy()
method is called to release resources.
o Diagram:
lua
Copy code
+---------------------+
| Client |
+---------------------+
|
v
+---------------------+
| Servlet Request |
+---------------------+
|
v
+---------------------+
| init() |
+---------------------+
|
v
+---------------------+
| service() |
+---------------------+
|
v
+---------------------+
| destroy() |
+---------------------+
• Answer: An Armstrong number is a number that is equal to the sum of its digits raised to the
power of the number of digits. For example, 153 is an Armstrong number because
13+53+33=1531^3 + 5^3 + 3^3 = 15313+53+33=153.
java
Copy code
import java.util.Scanner;
• Answer:
An Adapter class in Java provides default implementations for listener interfaces that contain
multiple methods. It simplifies the code when we need to handle only a few events out of many
available in the interface. Instead of implementing all methods of an interface, we can extend an
adapter class and override only the methods we need.
o Common Adapter Classes in Java:
▪ MouseAdapter: Implements MouseListener.
▪ KeyAdapter: Implements KeyListener.
▪ WindowAdapter: Implements WindowListener.
▪ FocusAdapter: Implements FocusListener.
▪ ComponentAdapter: Implements ComponentListener.
Example:
java
Copy code
import java.awt.event.*;
import javax.swing.*;
• Answer:
Constructor Overloading is a technique in Java where a class can have multiple constructors with
different parameter lists. Overloaded constructors initialize objects in various ways.
Example:
java
Copy code
class Student {
String name;
int age;
// No-argument constructor
Student() {
name = "Unknown";
age = 0;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
s1.display();
s2.display();
s3.display();
}
}
• Answer:
AWT (Abstract Window Toolkit) provides a set of components for building graphical user
interfaces in Java.
o Components:
▪ Button: A clickable button component.
▪ Label: A non-editable text label.
▪ TextField: A single-line text input field.
▪ TextArea: A multi-line text input area.
▪ Checkbox: A box that can be checked or unchecked.
▪ Radio Button: A group of radio buttons, allowing only one selection.
▪ List: Displays a list of items for selection.
▪ Menu: Provides drop-down options in a menu bar.
f) List any five checked exceptions & explain them with examples.
• Answer: Checked exceptions are exceptions that must be caught or declared in the method signature.
o 1. IOException: Occurs during input-output operations.
java
Copy code
try {
FileReader file = new FileReader("test.txt");
} catch (IOException e) {
e.printStackTrace();
}
java
Copy code
try {
Connection conn = DriverManager.getConnection("db_url", "user",
"pass");
} catch (SQLException e) {
e.printStackTrace();
}
java
Copy code
try {
Class.forName("SomeClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
java
Copy code
try {
FileInputStream file = new FileInputStream("test.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
java
Copy code
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
• Answer: This program creates a simple Swing frame with menu options.
java
Copy code
import javax.swing.*;
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
This program sets up a JFrame with a menu bar containing a “File” menu with “Open” and “New” options.
i) The Java ______ specifications defines an application programming interface for communication
between the web server and the application program.
• Answer: a) Servlet
The Servlet specification provides a standard API for web-based applications to interact with web servers in
Java.
• Answer: d) Interim
The JDBC-ODBC bridge is an interim solution to allow Java applications to communicate with databases via
ODBC drivers.
• Answer: b) JComponent
JComponent is the root base class in Swing for all visual UI components.
iv) ______ class writes primitive Java data types to an output stream in a portable way.
• Answer: d) DataOutputStream
The DataOutputStream class allows primitive data types to be written to output streams in a machine-
independent format.
• Answer: b) Package
A package in Java is a namespace that groups related classes and interfaces together.
• Answer:
Java is platform-neutral because it uses the Java Virtual Machine (JVM) to execute bytecode, which allows
Java programs to run on any operating system or hardware that has a compatible JVM.
ii) What is a final class?
• Answer:
A final class is a class that cannot be subclassed or extended. Using the final keyword before a class
prevents other classes from inheriting it, ensuring that its implementation cannot be altered through
inheritance.
• Answer:
Some classes that implement the List interface include:
o ArrayList
o LinkedList
o Vector
• Answer:
A listener in Java is an object that waits for events, such as user interactions (e.g., mouse clicks or key
presses), and responds by executing specific methods when those events occur.
• Answer:
Two implicit objects in JSP are:
o request: Represents the HTTP request sent by the client.
o response: Represents the HTTP response that the server sends back to the client.
Answer: JDBC (Java Database Connectivity) provides four types of drivers to connect Java applications to
databases:
Answer:
Answer:
1. Platform Independence: Java programs run on the Java Virtual Machine (JVM), making them
platform-independent, or "write once, run anywhere."
2. Object-Oriented: Java is an object-oriented language, which means it follows principles like
encapsulation, inheritance, and polymorphism.
3. Simple: Java has a clean syntax that’s easy to learn for programmers familiar with languages like
C++.
4. Secure: Java provides security features such as the sandbox environment and bytecode verification,
making it suitable for networked applications.
5. Multithreaded: Java supports multithreading, allowing programs to perform multiple tasks
simultaneously, which enhances performance.
Answer:
An Exception is an event that disrupts the normal flow of program execution. Java handles exceptions using
try, catch, and finally blocks.
• try: The try block contains code that might throw an exception.
• catch: The catch block handles the exception if it occurs. You can specify the type of exception to
catch.
• finally: The finally block contains code that will execute regardless of whether an exception is
caught or not. It’s often used to release resources.
Example:
java
Copy code
try {
int data = 10 / 0; // May throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("Execution complete");
}
Answer: The MVC (Model-View-Controller) architecture divides an application into three components:
1. Model: Manages data and business logic. It represents the state of the application.
2. View: Displays the data and represents the user interface. The view retrieves data from the model.
3. Controller: Handles user inputs and modifies the model and view accordingly.
This separation improves code organization, making it easier to manage, test, and update. Changes to the
user interface do not affect the model, and vice versa.
Answer:
• Built-in Packages: These are standard packages provided by Java, which include various classes and
interfaces for tasks like I/O, networking, utilities, and more. Examples include java.lang,
java.util, java.io, and java.net.
• User-Defined Packages: These are custom packages created by the programmer to organize classes
by functionality, reducing code clutter and enabling reuse. To create a package, the package
keyword is used at the beginning of a file.
java
Copy code
package com.example; // Declaring package
public class MyClass {
public void display() {
System.out.println("This is a user-defined package.");
}
}
a) Write a Java program to display last access and current date using session.
Answer:
This Java program demonstrates how to use session tracking to display the last access date and the current
date.
java
Copy code
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class SessionExample extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
Explanation:
Answer:
1. TYPE_FORWARD_ONLY:
o The default type.
o The cursor can only move forward through the result set.
o Example:
java
Copy code
Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
2. TYPE_SCROLL_INSENSITIVE:
o Allows the cursor to move both forward and backward.
o The result set is not sensitive to changes made to the underlying data after the query is
executed.
o Example:
java
Copy code
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
3. TYPE_SCROLL_SENSITIVE:
o Allows the cursor to move forward and backward, and it is sensitive to changes in the
underlying data.
o If the data changes after the query, the result set will reflect the changes.
o Example:
java
Copy code
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Answer:
Swing is a GUI toolkit in Java that provides a rich set of features for building user interfaces.
1. Lightweight Components:
o Swing components do not rely on native GUI components of the underlying operating
system. They are written entirely in Java.
o Example: JButton, JLabel, JTextField.
2. Pluggable Look and Feel:
o Swing supports different "look and feels," allowing the user interface to resemble the style of
different operating systems (e.g., Windows, Motif, or cross-platform styles).
3. Event Handling:
o Swing provides a robust event handling mechanism for user interactions. Events like button
clicks or mouse movements can be easily captured and processed.
4. Rich Set of Components:
o Swing provides a variety of advanced GUI components, such as tables (JTable), text areas
(JTextArea), and trees (JTree).
5. Built-in Layout Managers:
o Swing supports several layout managers (e.g., FlowLayout, BorderLayout, GridLayout,
etc.) that help in arranging components in a container.
e) Explain any four methods of the StringBuffer class with proper syntax.
Answer:
1. append(String str):
o Adds the specified string to the end of the current string buffer.
java
Copy code
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World
java
Copy code
StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " World");
System.out.println(sb); // Output: Hello World
java
Copy code
StringBuffer sb = new StringBuffer("Hello World");
sb.delete(5, 11);
System.out.println(sb); // Output: Hello
4. reverse():
o Reverses the contents of the string buffer.
java
Copy code
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); // Output: olleH
Answer:
An interface in Java is a collection of abstract methods. A class implements an interface to define the
behavior specified by the interface.
To implement an interface:
java
Copy code
// Interface definition
interface Animal {
void sound(); // Abstract method
}
Answer:
A constructor is a special method in a class that is invoked when an object of that class is created. It
initializes the object.
Types of Constructors:
1. Default Constructor:
o A constructor that takes no arguments. It is automatically provided by Java if no constructors
are explicitly defined.
o Example:
java
Copy code
class MyClass {
MyClass() {
System.out.println("Default Constructor");
}
}
2. Parameterized Constructor:
o A constructor that takes arguments and allows initializing objects with specific values.
o Example:
java
Copy code
class MyClass {
int x;
MyClass(int value) {
x = value;
}
}
Q4) Answer the following in detailed and with example (Any Five): [5 × 5 = 25]
a) Write a Java program that accepts array elements and prints the average of all elements.
Answer:
java
Copy code
import java.util.Scanner;
Explanation:
Answer:
1. ArrayList:
o A resizable array implementation of the List interface.
o Allows dynamic resizing and provides fast random access.
o Example:
java
Copy code
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
2. HashSet:
o Implements the Set interface and stores unique elements.
o Does not maintain any order.
o Example:
java
Copy code
HashSet<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
3. LinkedList:
o Implements the List interface and allows inserting elements at any position.
o Provides better performance than ArrayList for operations like insertion and deletion.
o Example:
java
Copy code
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("First");
linkedList.add("Second");
4. HashMap:
o Implements the Map interface and stores key-value pairs.
o Allows quick lookup of values by key.
o Example:
java
Copy code
HashMap<String, Integer> map = new HashMap<>();
map.put("John", 25);
map.put("Emma", 30);
5. TreeSet:
o A Set implementation that stores elements in sorted order.
o Example:
java
Copy code
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(50);
treeSet.add(20);
treeSet.add(10);
Answer:
• Event: An event is an action that occurs in response to user interaction, such as clicking a button,
typing a key, or moving the mouse. In AWT (Abstract Window Toolkit), events are objects that
represent user interactions.
• Event Handling in AWT:
o In AWT, events are handled by defining event listeners. These listeners implement specific
interfaces, such as ActionListener for button clicks or MouseListener for mouse events.
Example:
java
Copy code
import java.awt.*;
import java.awt.event.*;
frame.add(button);
frame.setSize(300, 200);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
}
}
Explanation:
Answer:
Answer:
• Servlet: A servlet is a Java class that extends the capabilities of servers. It runs on a server and
handles requests from clients (usually web browsers). It can generate dynamic content like HTML.
Types of Servlets:
1. Generic Servlet:
o The GenericServlet class implements the Servlet interface and provides default behavior
for handling requests.
o Example:
java
Copy code
public class MyServlet extends GenericServlet {
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
// Code to handle request
}
}
2. HTTP Servlet:
o A subclass of GenericServlet specifically designed for handling HTTP requests.
o Commonly used to create web applications.
o Methods like doGet(), doPost(), etc., are used to handle different HTTP methods.
o Example:
java
Copy code
public class MyHttpServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
// Handle GET request
}
}
f) Create a student table with fields (roll-no, name, percentage). Write a JDBC program to insert,
delete & display details.
Answer:
java
Copy code
import java.sql.*;
// Insert data
String insertSQL = "INSERT INTO student (roll_no, name, percentage) VALUES
(?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(insertSQL);
pstmt.setInt(1, 1);
pstmt.setString(2, "John");
pstmt.setDouble(3, 85.5);
pstmt.executeUpdate();
// Display data
String selectSQL = "SELECT * FROM student";
ResultSet rs = stmt.executeQuery(selectSQL);
while (rs.next()) {
System.out.println("Roll No: " + rs.getInt("roll_no") + ", Name: " +
rs.getString("name") + ", Percentage: " + rs.getDouble("percentage"));
}
// Delete data
String deleteSQL = "DELETE FROM student WHERE roll_no = ?";
pstmt = conn.prepareStatement(deleteSQL);
pstmt.setInt(1, 1);
pstmt.executeUpdate();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Explanation:
• The program creates a student table with columns roll_no, name, and percentage.
• It inserts a student record, displays all records, and then deletes a record.
g) Write a Java program that accepts a number from the user and displays the factorial of it (use
Swing & ActionListener).
Answer:
java
Copy code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int num = Integer.parseInt(textField.getText());
long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
resultLabel.setText("Factorial: " + factorial);
}
});
frame.add(label);
frame.add(textField);
frame.add(button);
frame.add(resultLabel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Explanation:
• This program creates a simple Swing interface where the user can input a number and click a button
to calculate its factorial.
• An ActionListener is used to trigger the calculation and display the result in a label.