advance java model paper
advance java model paper
1.A] What is an Enum? Write a program that displays enumeration constants using
the values() and valueOf() methods.
An Enum (short for Enumeration) in Java is a special data type that enables for a variable to
be a set of predefined constants. It is used to represent a fixed set of constants, such as days
of the week, directions, or seasons. Enums are type-safe, meaning you can only assign values
that are within the predefined set, preventing errors caused by invalid values.
// Define an enum named Day with constants representing the days of the week
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}
Autoboxing is the automatic conversion that the Java compiler makes between the
primitive data types (e.g., int, char, boolean, etc.) and their corresponding object wrapper
classes (e.g., Integer, Character, Boolean, etc.).
Unboxing is the reverse process, where the object wrapper class is automatically
converted back to the corresponding primitive type.
Example of Autoboxing:
public class AutoboxingExample {
public static void main(String[] args) {
// Autoboxing: primitive int is converted to Integer object
int num = 100;
Integer boxedNum = num; // Autoboxing
System.out.println("Boxed Integer: " + boxedNum);
}
}
Example of Unboxing:
In Java, primitive data types (e.g., int, char, boolean) have corresponding object wrapper
classes, collectively known as “Type Wrappers.” These wrapper classes are part of
the java.lang package and provide a way to treat primitive values as objects.
Common Wrapper Classes:
int → Integer
char → Character
boolean → Boolean
float → Float
double → Double
Example of Using Type Wrapper:
public class WrapperExample {
public static void main(String[] args) {
// Create an Integer object using the Integer wrapper class
Integer numObject = Integer.valueOf(10); // Boxing manually
System.out.println("Integer object: " + numObject);
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
Explanation:
@Retention(RetentionPolicy.RUNTIME): This means the annotation will be available at runtime.
@Target(ElementType.METHOD): This means the annotation can be applied to methods.
The annotation has a single element value(), which returns a String.
Step 2: Use the Single-Member Annotation in a Program
public class SingleMemberAnnotationExample {
System.out.println("myMethod is executed.");
obj.myMethod();
.getAnnotation(MyAnnotation.class);
Explanation:
1. Annotation Usage:
The @MyAnnotation("Hello, this is a single-member annotation!") is applied to the myMethod() method.
The value "Hello, this is a single-member annotation!" is assigned to the single member value().
1. Accessing the Annotation:
In the main() method, the program uses reflection to access the MyAnnotation annotation
applied to the myMethod() method.
The value() of the annotation is then printed out.
Reflection is a powerful feature in Java that allows a program to inspect and modify
the structure and behavior of classes, interfaces, fields, and methods at runtime.
When it comes to annotations, reflection can be used to obtain and manipulate
annotations applied to various elements (e.g., classes, methods, fields) during
runtime.
Steps to Obtain Annotations at Runtime:-
1. Define an Annotation: First, you need to define an annotation if it doesn’t already exist.
2. Apply the Annotation: Apply the annotation to classes, methods, fields, or constructors.
3. Use Reflection to Retrieve the Annotation: At runtime, you can use
the java.lang.reflect package to retrieve annotations.
Example Program: Retrieving Annotations at Runtime
Let’s create an annotation called MyRuntimeAnnotation, apply it to a method, and then
retrieve it at runtime using reflection.
Step 1: Define the Annotation
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyRuntimeAnnotation {
Explanation:
@Retention(RetentionPolicy.RUNTIME): This retention policy ensures that the annotation is
available at runtime.
@Target(ElementType.METHOD): Specifies that the annotation can be applied to methods.
String description(): A single element of the annotation that holds a description.
Step 2: Apply the Annotation
public class ReflectionExample {
Explanation:
The @MyRuntimeAnnotation is applied to the annotatedMethod() method with a description value.
Step 3: Use Reflection to Retrieve the Annotation
import java.lang.reflect.Method;
try {
if (method.isAnnotationPresent(MyRuntimeAnnotation.class)) {
method.invoke(example);
} catch (Exception e) {
e.printStackTrace();
Explanation:
1. Retrieving the Method Object:
The Method object representing the annotatedMethod() is retrieved
using getMethod("annotatedMethod").
1. Checking for the Annotation:
The isAnnotationPresent() method checks if the MyRuntimeAnnotation is present on the method.
1. Accessing the Annotation:
The getAnnotation() method retrieves the annotation, and its element description() is accessed
and printed.
1. Invoking the Method:
The method.invoke() call runs the annotatedMethod() to demonstrate that the method works
normally.
Module 2
class Box<T> {
private T content;
this.content = content;
public T getContent() {
return content;
Explanation:
The Box class has a type parameter T.
T can be any type, and the class will operate on this type.
setContent() method sets the content of the box, and getContent() retrieves it.
Step 2: Use the Generic Class
public class GenericsExample {
integerBox.setContent(123);
stringBox.setContent("Hello Generics!");
}
}
Explanation:
Box<Integer>: Creates a Box instance that holds Integer values.
Box<String>: Creates a Box instance that holds String values.
The setContent() and getContent() methods work with the type specified ( Integer or String).
Answer:
Generics in Java enhance type safety by enabling you to specify and enforce the type
of objects that can be used with classes, interfaces, and methods. This helps catch
type-related errors at compile time, reducing runtime errors and making your code
more reliable and easier to maintain.
Key Ways Generics Improve Type Safety
1. Compile-Time Type Checking Generics allow the compiler to enforce type constraints on
parameters, fields, and methods. This means that the compiler can check that only objects of
the specified type are used, catching type errors during the compilation process. Example:
import java.util.ArrayList;
integerList.add(1); // Valid
integerList.add(2); // Valid
Explanation:
The ArrayList is parameterized with Integer, so only Integer objects can be added to it.
Attempting to add a String results in a compile-time error, preventing runtime type
mismatch issues.
2. Elimination of Explicit Casting With generics, you no longer need to explicitly
cast objects when retrieving them from collections. This reduces the risk
of ClassCastException and makes the code cleaner.
Example:
import java.util.ArrayList;
public class NoCastingExample {
public static void main(String[] args) {
// Create an ArrayList for Integer
ArrayList<Integer> integerList = new ArrayList<>();
integerList.add(10);
integerList.add(20);
// Retrieving elements does not require explicit casting
Integer firstElement = integerList.get(0);
System.out.println("First element: " + firstElement);
}
}
Explanation:
The ArrayList is parameterized with Integer, so integerList.get(0) directly returns an Integer,
avoiding the need for type casting.
3. Prevention of Runtime Errors By enforcing type constraints at compile time,
generics help prevent common runtime errors related to type mismatches. This
results in fewer bugs and more predictable code behavior.
Example:
import java.util.HashMap;
public class SafeMapExample {
public static void main(String[] args) {
// Create a HashMap with String keys and Integer values
HashMap<String, Integer> map = new HashMap<>();
map.put("key1", 100);
map.put("key2", 200);
// The following line would cause a compile-time error
// map.put(123, "value"); // Error: incompatible types
}
}
Explanation:
The HashMap is parameterized with String keys and Integer values. Attempting to use
incorrect types will result in compile-time errors, thus avoiding potential runtime
issues.
4. Type Inference Generics allow for type inference, which reduces the need to
specify the type explicitly in certain cases, making the code more concise while
maintaining type safety.
Example:
import java.util.ArrayList;
public class TypeInferenceExample {
public static void main(String[] args) {
// Type inference with the diamond operator
ArrayList<String> stringList = new ArrayList<>();
stringList.add("Hello");
stringList.add("World");
// Retrieving elements
String firstElement = stringList.get(0);
System.out.println("First element: " + firstElement);
}
}
Explanation:
The diamond operator <> allows the compiler to infer the type parameter from the
context, making the code shorter while preserving type safety.
System.out.println(num);
list.add(10);
list.add(20);
Summary: Bounded wildcards are a powerful feature in Java generics that provide
more control over what types can be used in generic classes and methods. They
enhance flexibility while maintaining type safety.
ii) Erasure
Type Erasure is the process by which the Java compiler removes generic type
information during the compilation of code.
This means that after compilation, the bytecode contains only non-generic versions
of classes, methods, and interfaces. This process ensures backward compatibility with
older versions of Java that did not support generics.
How Erasure Works:
1. Replace Type Parameters: During compilation, the compiler replaces all generic type
parameters with their bound types (or Object if no bound is specified). For
example, List<T> might become List<Object>.
2. Insert Casts: Where necessary, the compiler inserts type casts to ensure type safety. For
instance, when retrieving elements from a generic collection, it adds the appropriate cast to
convert the object back to the expected type.
3. Remove Generic Information: Finally, the compiler removes all generic type information
from the compiled bytecode, meaning the runtime has no knowledge of the generic types.
Example Before Erasure:
public class Box<T> {
private T value;
this.value = value;
public T get() {
return value;
this.value = value;
return value;
Implications of Erasure:
1. No Runtime Type Information: Because type information is erased, you cannot perform
certain operations at runtime, such as checking the type of a generic parameter ( if (obj
instanceof T) is not allowed).
2. Type Safety via Casts: The compiler adds type casts where necessary, but this can lead
to ClassCastException at runtime if the code is not used correctly.
3. Overloading Restrictions: Since type erasure removes generic information, methods that
differ only by generic type parameters cannot be overloaded. For example, void
print(List<String> list) and void print(List<Integer> list) cannot coexist.
Module 3
5.B] What are the different character extraction methods? Explain with a
program.
Answer:
Java provides several methods to extract characters or sequences of characters from
a String object. These methods are useful for retrieving specific characters, substrings,
or sequences from strings.
1. charAt(int index)
Extracts a single character at a specified index.
Syntax: char ch = str.charAt(index);
Example:
String str = "Hello";
char ch = str.charAt(1);
3. toCharArray()
Converts the entire string into a character array.
Syntax: char[] charArray = str.toCharArray();
Example:
String str = "Hello";
4. substring(int beginIndex)
Extracts a substring from the specified begin index to the end of the string.
Syntax: String subStr = str.substring(beginIndex);
Example:
String str = "Hello";
6.A] Define String handling. Explain special string operations with examples.
Answer:-
String handling in Java refers to the process of creating, manipulating, and
managing strings. Strings in Java are objects that represent sequences of characters.
The String class provides various methods and operations for handling these
sequences efficiently.
Special String Operations
Java provides several special operations for handling strings, which include
concatenation, comparison, searching, modifying, and more.
1. String Concatenation
Combines two or more strings into one.
Syntax:
String result = str1 + str2;
or
String result = str1.concat(str2);
Example:
String str1 = "Hello";
2. String Comparison
Compares two strings for equality or order.
Methods:
equals(): Checks if two strings are exactly the same.
equalsIgnoreCase(): Compares strings without considering case.
compareTo(): Compares strings lexicographically.
compareToIgnoreCase(): Lexicographical comparison ignoring case.
Example:
String str1 = "Hello";
3. Substring Extraction
Extracts a portion of a string based on the specified index.
Methods:
substring(int beginIndex): Extracts from the specified index to the end.
substring(int beginIndex, int endIndex): Extracts between the specified indices.
Example:
String str = "HelloWorld";
4. String Length
Returns the number of characters in a string.
Method:
length(): Returns the length of the string.
Example:
String str = "HelloWorld";
int length = str.length();
5. String Replacement
Replaces characters or sequences of characters within a string.
Methods:
replace(char oldChar, char newChar): Replaces all occurrences of the old character with the new
character.
replace(CharSequence target, CharSequence replacement): Replaces all occurrences of the target
sequence with the replacement sequence.
Example:
String str = "Hello World";
7. String Trimming
Removes leading and trailing whitespace from a string.
Method:
trim(): Removes whitespace from both ends of the string.
Example:
String str = " Hello World ";
sb.append(" World");
sb.delete(5, 11);
sb.deleteCharAt(4);
6. reverse()
Purpose: Reverses the sequence of characters in the StringBuffer.
Syntax: sb.reverse();
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
sb.setCharAt(1, 'a');
8. setLength(int newLength)
Purpose: Sets the length of the StringBuffer. If the new length is greater than the current
length, null characters (\u0000) are added. If it’s less, the string is truncated.
Syntax: sb.setLength(newLength);
Example:
StringBuffer sb = new StringBuffer("Hello");
sb.setLength(2);
System.out.println(sb); // Output: He
9. capacity()
Purpose: Returns the current capacity of the StringBuffer (the amount of storage available for
new characters without resizing).
Syntax: int capacity = sb.capacity();
Example:
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // Output: 16 (default capacity)
sb.ensureCapacity(30);
System.out.println(sb.capacity()); // Output: 30
11. length()
Purpose: Returns the number of characters stored in the StringBuffer.
Syntax: int len = sb.length();
Example:
StringBuffer sb = new StringBuffer("Hello");
System.out.println(sb.length()); // Output: 5
System.out.println(subStr);
Module 4
7.A] List and explain core classes and interfaces in the javax.servlet package.
Answer:
INTERFACES CLASSES
Servlet ServletInputStream
ServletContext ServletOutputStream
ServletConfig ServletException
ServletRequest UnavailableException
ServletResponse GenericServlet
Interface Summary
Defines a set of methods that a servlet uses to communicate with its servlet container, for
ServletContext
example, to get the MIME type of a file, dispatch requests, or write to a log file.
Class Summary
Provides an input stream for reading binary data from a client request, including an
ServletInputStream
efficient readLine method for reading data one line at a time.
ServletOutputStream Provides an output stream for sending binary data to the client.
ServletException Defines a general exception a servlet can throw when it encounters difficulty.
import javax.servlet.http.*;
import java.io.IOException;
public class QueryParamServlet extends HttpServlet {
@Override
res.setContentType("text/html");
out.println("<html><body>");
out.println("<h1>Query Parameters</h1>");
out.println("</body></html>");
2. Form Parameters
Purpose: Parameters sent via an HTML form using either the GET or POST method.
Method to Use: getParameter(String name)
Example HTML Form:
<form action="formServlet" method="post">
<label for="name">Name:</label>
<label for="age">Age:</label>
</form>
Example Servlet Code:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
@Override
res.setContentType("text/html");
out.println("<html><body>");
out.println("<h1>Form Parameters</h1>");
out.println("</body></html>");
import javax.servlet.http.*;
import java.io.IOException;
@Override
res.setContentType("text/html");
out.println("<html><body>");
out.println("<h1>Path Parameters</h1>");
out.println("</body></html>");
8.A] Explain how to handle HTTP request and response with an example
Answer:
In Java servlets, handling HTTP requests and responses involves overriding methods
from the HttpServlet class. The most common methods are doGet() and doPost(), which
correspond to HTTP GET and POST requests, respectively. Here’s a breakdown of how
to handle these requests and responses with examples.
Common HTTP Methods
1. GET Method
Purpose: Retrieves data from the server.
Usage: Often used for requesting data or resources.
Characteristics: Parameters are sent in the URL.
Example URL: http://example.com/servlet?param1=value1¶m2=value2
2. POST Method
Purpose: Submits data to be processed by the server.
Usage: Often used for form submissions and data modifications.
Characteristics: Parameters are sent in the body of the request, not in the URL.
Example: Handling HTTP Requests and Responses
1. HTML Form for GET and POST Requests
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<h2>GET Request</h2>
</form>
<h2>POST Request</h2>
</form>
</body>
</html>
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
public class GetServlet extends HttpServlet {
@Override
response.setContentType("text/html");
// Generate response
out.println("<html><body>");
out.println("<h2>GET Request</h2>");
out.println("</body></html>");
out.close();
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
// Generate response
out.println("<html><body>");
out.println("<h2>POST Request</h2>");
out.println("</body></html>");
out.close();
Explanation
1. HTML Form:
GET Form: Submits data using the GET method, appending parameters to the URL.
POST Form: Submits data using the POST method, including parameters in the request
body.
2. Servlets:
doGet() Method: Handles GET requests. Retrieves parameters from the URL and generates a
response.
doPost() Method: Handles POST requests. Retrieves parameters from the request body and
generates a response.
Differences Between GET and POST Requests:
Feature GET Request POST Request
Data Data is visible in the URL query string. Suitable for Data is included in the request body. Suitable for
Visibility non-sensitive data. sensitive data and larger amounts of data.
Idempotent; multiple identical GET requests should Not necessarily idempotent; each request can have
Idempotency
have the same effect as a single request. a different effect.
Caching Requests can be cached by browsers and servers. Requests are generally not cached.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Module 5
JDBC is used to interact with various type of Database such as Oracle, MS Access, My
SQL and SQL Server.
JDBC can also be defined as the platform-independent interface between a relational
database and Java programming.
It allows java program to execute SQL statement and retrieve result from database.
JDBC Driver is a software component that enables java application to interact with
the database.
There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
This is now discouraged because of thin driver.
Advantages:
easy to use.
o can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database.
The driver converts JDBC method calls into native calls of the database API.
It is not written entirely in java.
Advantage:
performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol.
It is fully written in java.
Advantage:
No client side library is required because of application server that can perform many tasks
like auditing, load balancing, logging etc.
Disadvantages:
Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver.
It is fully written in Java language.
Advantage:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depends on the Database.
9.B] Describe various steps of JDBC with code snippets.
Answer:-
ResultSet rs = st.executeQuery(sql);
}
5. Close the Connection Object
Purpose: Close the ResultSet, Statement, and Connection to release resources.
Methods: rs.close(), st.close(), con.close()
rs.close();
st.close();
con.close();
cs = conn.prepareCall(SQL);
"{call getEmpName (?, ?)}" specifies the stored procedure getEmpName with two parameters.
1. Set Input Parameters:
cs.setInt(1, 100);
cs.setInt(1, 100); sets the first parameter (employee ID) to 100.
1. Register Output Parameters:
cs.registerOutParameter(2, Types.VARCHAR);
cs.registerOutParameter(2, Types.VARCHAR); registers the second parameter as an output
parameter of type VARCHAR.
1. Execute the CallableStatement:
cs.execute();
Executes the stored procedure.
1. Retrieve Output Parameter:
String Name = cs.getString(2);
Retrieves the output parameter value, which is the employee’s first name.
1. Close the CallableStatement:
cs.close();
Closes the CallableStatement to release resources.