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

advance java model paper

The document provides an overview of various Java programming concepts including Enums, Autoboxing, Unboxing, Type Wrappers, single-member annotations, and Generics. It includes example programs demonstrating these concepts, such as using Enums to represent days of the week, implementing Autoboxing and Unboxing, and defining a generic class and interface. Additionally, it discusses the benefits of Generics in enhancing type safety and provides examples of Bounded Wildcards and Erasure.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

advance java model paper

The document provides an overview of various Java programming concepts including Enums, Autoboxing, Unboxing, Type Wrappers, single-member annotations, and Generics. It includes example programs demonstrating these concepts, such as using Enums to represent days of the week, implementing Autoboxing and Unboxing, and defining a generic class and interface. Additionally, it discusses the benefits of Generics in enhancing type safety and provides examples of Bounded Wildcards and Erasure.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Module 1

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
}

public class EnumExample {


public static void main(String[] args) {
// Use the values() method to get an array of all enum constants
Day[] daysOfWeek = Day.values();

// Display each constant using a loop


System.out.println("Days of the week:");
for (Day day : daysOfWeek) {
System.out.println(day);
}

// Use the valueOf() method to convert a string to an enum constant


Day today = Day.valueOf("MONDAY");

// Display the result


System.out.println("\nToday is: " + today);
}
}

1.B] Explain with examples:


i) Autoboxing and Unboxing
ii) Type Wrapper

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:

public class UnboxingExample {


public static void main(String[] args) {
// Unboxing: Integer object is converted to primitive int
Integer boxedNum = 200;
int num = boxedNum; // Unboxing
System.out.println("Unboxed int: " + num);
}
}

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);

// Convert Integer object back to primitive int


int numPrimitive = numObject.intValue(); // Unboxing manually
System.out.println("Primitive int: " + numPrimitive);

// Use of utility methods from wrapper class


String binaryString = Integer.toBinaryString(numPrimitive);
System.out.println("Binary representation: " + binaryString);
}
}

2.A] Explain single-member annotations with a program example.


Answer:
A single-member annotation is a special type of annotation that has only one
element (also known as a member or attribute). In such annotations, you don’t need
to specify the name of the element when you use it, as there is only one element to
set. This single element is defined using the special method name value().
Example of a Single-Member Annotation:
Let’s create a single-member annotation called MyAnnotation and use it in a program.
Step 1: Define the Single-Member Annotation
import java.lang.annotation.*;

// Define the annotation with a single element

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

@interface MyAnnotation {

String value(); // Single-member element

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 {

// Applying the single-member annotation to a method

@MyAnnotation("Hello, this is a single-member annotation!")

public void myMethod() {

System.out.println("myMethod is executed.");

public static void main(String[] args) throws Exception {

SingleMemberAnnotationExample obj = new SingleMemberAnnotationExample();

obj.myMethod();

// Accessing the annotation

MyAnnotation annotation = obj.getClass()


.getMethod("myMethod")

.getAnnotation(MyAnnotation.class);

System.out.println("Annotation value: " + annotation.value());

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.

2.B] Describe how to obtain annotations at runtime using Reflection.

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.*;

// Define an annotation with runtime retention

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

@interface MyRuntimeAnnotation {

String description(); // Define an element in the annotation


}

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 {

// Apply the annotation to a method

@MyRuntimeAnnotation(description = "This is a method annotation example.")

public void annotatedMethod() {

System.out.println("Annotated method is running.");

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;

public class AnnotationRetrievalExample {

public static void main(String[] args) {

try {

// Create an instance of the class containing the annotated method

ReflectionExample example = new ReflectionExample();

// Get the Method object for the annotated method

Method method = example.getClass().getMethod("annotatedMethod");

// Check if the method has the annotation

if (method.isAnnotationPresent(MyRuntimeAnnotation.class)) {

// Get the annotation

MyRuntimeAnnotation annotation = method.getAnnotation(MyRuntimeAnnotation.class);


// Access the annotation's elements

System.out.println("Annotation description: " + annotation.description());

// Invoke the method

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

3.A] What are Generics? Provide an example program.


Answer:
Generics in Java are a feature that allows you to define classes, interfaces, and
methods with type parameters. This means you can create components that operate
on objects of various types while providing compile-time type safety. Generics enable
you to write more flexible and reusable code by allowing you to parameterize types.
Benefits of Generics:
1. Type Safety: Prevents runtime type errors by checking types at compile-time.
2. Code Reusability: Allows you to create classes, interfaces, and methods that can work with
any type.
3. Eliminates Casting: Removes the need for explicit type casting when retrieving elements
from a collection.
Example Program: Using Generics
Let’s create a simple generic class and demonstrate its usage.
Step 1: Define a Generic Class
// Define a generic class with type parameter T

class Box<T> {

private T content;

public void setContent(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 {

public static void main(String[] args) {

// Create a Box for Integer

Box<Integer> integerBox = new Box<>();

integerBox.setContent(123);

System.out.println("Integer content: " + integerBox.getContent());

// Create a Box for String

Box<String> stringBox = new Box<>();

stringBox.setContent("Hello Generics!");

System.out.println("String content: " + stringBox.getContent());

}
}

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).

3b)How Generics Improve Type Safety

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;

public class TypeSafetyExample {

public static void main(String[] args) {

// Create an ArrayList that only accepts Integer objects

ArrayList<Integer> integerList = new ArrayList<>();

integerList.add(1); // Valid

integerList.add(2); // Valid

// The following line would cause a compile-time error

// integerList.add("String"); // Error: incompatible types

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.

4.A] Write a program using a Generic Interface.


Answer:
// Define a generic interface
interface SimpleCalculator<T> {
T add(T a, T b);
T subtract(T a, T b);
}
// Implement the generic interface for Integer type
class IntegerCalculator implements SimpleCalculator<Integer> {
@Override
public Integer add(Integer a, Integer b) {
return a + b;
}
@Override
public Integer subtract(Integer a, Integer b) {
return a - b;
}
}
// Main class to test the implementation
public class Main {
public static void main(String[] args) {
// Use the IntegerCalculator
SimpleCalculator<Integer> calculator = new IntegerCalculator();
// Perform addition and subtraction
System.out.println("Addition: " + calculator.add(2, 3)); // Output: 5
System.out.println("Subtraction: " + calculator.subtract(5, 3)); // Output: 2
}
}

4.B] Write a note on:


i) Bounded Wildcards
ii) Erasure
Answer:
i) Bounded Wildcards
Bounded Wildcards in Java generics are a way to restrict the types that can be
passed as arguments to a generic method or class.
They allow you to specify an upper or lower bound for the type parameter, making
the code more flexible while still enforcing some type safety.
Types of Bounded Wildcards:
1. Upper Bounded Wildcards (<? extends T>):
 Restricts the type to be a subtype of T.
 Useful when you want to read from a generic structure but not modify it.
 Example: List<? extends Number> means the list can hold objects of type Number or its
subclasses like Integer, Double, etc. Example:
public static void printNumbers(List<? extends Number> list) {

for (Number num : list) {

System.out.println(num);

2. Lower Bounded Wildcards (<? super T>):


 Restricts the type to be a supertype of T.
 Useful when you want to write to a generic structure but not read from it.
 Example: List<? super Integer> means the list can hold Integer and any of its supertypes
like Number or Object. Example:
public static void addNumbers(List<? super Integer> list) {

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;

public void set(T value) {

this.value = value;

public T get() {

return value;

Example After Erasure:


public class Box {

private Object value;


public void set(Object value) {

this.value = value;

public Object get() {

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.A] Explain different types of String Constructors with examples.


Answer:-
Java provides several constructors to create String objects. Each constructor serves a
specific purpose and allows the creation of strings in different ways.
1. Default Constructor
 Creates an empty String object.
 Syntax: String str = new String();
 Example:
String str = new String();

System.out.println("String: '" + str + "'"); // Output: String: ''

2. String Literal Constructor


 Directly assigns a string literal to a String variable. Although it’s not a constructor, it’s the
most common way to create a String.
 Syntax: String str = "Hello";
 Example:
String str = "Hello";

System.out.println(str); // Output: Hello

3. Constructor with String Argument


 Creates a new String object that is a copy of the argument string.
 Syntax: String str = new String(String anotherString);
 Example:
String original = "Hello";

String copy = new String(original);

System.out.println(copy); // Output: Hello

4. Constructor with char[] Array


 Creates a String object from a character array.
 Syntax: String str = new String(char[] charArray);
 Example:
char[] charArray = {'H', 'e', 'l', 'l', 'o'};

String str = new String(charArray);

System.out.println(str); // Output: Hello

5. Constructor with char[] Array and Offset


 Creates a String object from a portion of a character array, specified by an offset and a count.
 Syntax: String str = new String(char[] charArray, int offset, int count);
 Example:
char[] charArray = {'H', 'e', 'l', 'l', 'o'};

String str = new String(charArray, 1, 3);

System.out.println(str); // Output: ell

6. Constructor with byte[] Array


 Creates a String object from a byte array. Each byte is interpreted as a character.
 Syntax: String str = new String(byte[] byteArray);
 Example:
byte[] byteArray = {72, 101, 108, 108, 111};

String str = new String(byteArray);

System.out.println(str); // Output: Hello

7. Constructor with byte[] Array and Charset


 Creates a String object from a byte array using a specified charset.
 Syntax: String str = new String(byte[] byteArray, Charset charset);
 Example:
byte[] byteArray = {72, 101, 108, 108, 111};

String str = new String(byteArray, Charset.forName("UTF-8"));

System.out.println(str); // Output: Hello


8. Constructor with int[] Array
 Creates a String object from an array of Unicode code points.
 Syntax: String str = new String(int[] codePoints, int offset, int count);
 Example:
int[] codePoints = {72, 101, 108, 108, 111};

String str = new String(codePoints, 0, 5);

System.out.println(str); // Output: Hello

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);

System.out.println("Character at index 1: " + ch); // Output: e

2. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


 Extracts a sequence of characters from a string and stores them in a character array.
 Syntax: str.getChars(srcBegin, srcEnd, dst, dstBegin);
 Example:
String str = "Hello";

char[] dst = new char[3];

str.getChars(1, 4, dst, 0);

System.out.println("Extracted characters: " + new String(dst)); // Output: ell

3. toCharArray()
 Converts the entire string into a character array.
 Syntax: char[] charArray = str.toCharArray();
 Example:
String str = "Hello";

char[] charArray = str.toCharArray();


System.out.println("Character array: " + Arrays.toString(charArray)); // Output: [H, e, l, l, o]

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";

String subStr = str.substring(2);

System.out.println("Substring from index 2: " + subStr); // Output: llo

5. substring(int beginIndex, int endIndex)


 Extracts a substring from the specified begin index to the specified end index.
 Syntax: String subStr = str.substring(beginIndex, endIndex);
 Example:
String str = "Hello";

String subStr = str.substring(1, 4);

System.out.println("Substring from index 1 to 4: " + subStr)

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";

String str2 = "World";

String result = str1 + " " + str2;


System.out.println(result); // Output: Hello World

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";

String str2 = "hello";

boolean isEqual = str1.equals(str2);

boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2);

int comparison = str1.compareTo(str2);

System.out.println("isEqual: " + isEqual); // Output: false

System.out.println("isEqualIgnoreCase: " + isEqualIgnoreCase); // Output: true

System.out.println("comparison: " + comparison); // Output: negative value

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";

String subStr1 = str.substring(5);

String subStr2 = str.substring(0, 5);

System.out.println("subStr1: " + subStr1); // Output: World

System.out.println("subStr2: " + subStr2); // Output: Hello

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();

System.out.println("Length: " + length); // Output: 10

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";

String replacedStr = str.replace('o', 'a');

String replacedStr2 = str.replace("World", "Java");

System.out.println("replacedStr: " + replacedStr); // Output: Hella Warld

System.out.println("replacedStr2: " + replacedStr2); // Output: Hello Java

6. String Case Conversion


 Converts strings to upper or lower case.
 Methods:
 toUpperCase(): Converts all characters in the string to uppercase.
 toLowerCase(): Converts all characters in the string to lowercase.
 Example:
String str = "Hello World";

String upperCaseStr = str.toUpperCase();

String lowerCaseStr = str.toLowerCase();

System.out.println("upperCaseStr: " + upperCaseStr); // Output: HELLO WORLD

System.out.println("lowerCaseStr: " + lowerCaseStr); // Output: 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 ";

String trimmedStr = str.trim();

System.out.println("trimmedStr: '" + trimmedStr + "'");


6.B] Explain all String Buffer methods with examples.
Answer:
The StringBuffer class in Java is used to create mutable (modifiable) strings.
Unlike String, which is immutable, StringBuffer allows strings to be changed without
creating new objects. Below are some of the commonly used StringBuffer methods
along with examples.
1. append(String str)
 Purpose: Adds the specified string to the end of the current StringBuffer.
 Syntax: sb.append(str);
 Example:
StringBuffer sb = new StringBuffer("Hello");

sb.append(" World");

System.out.println(sb); // Output: Hello World

2. insert(int offset, String str)


 Purpose: Inserts the specified string at the given offset (position) in the StringBuffer.
 Syntax: sb.insert(offset, str);
 Example:
StringBuffer sb = new StringBuffer("Hello World");

sb.insert(6, "Beautiful ");

System.out.println(sb); // Output: Hello Beautiful World

3. replace(int start, int end, String str)


 Purpose: Replaces the characters in the substring of this StringBuffer starting at the specified
start index and ending at the end index with the specified string.
 Syntax: sb.replace(start, end, str);
 Example:
StringBuffer sb = new StringBuffer("Hello World");

sb.replace(6, 11, "Java");

System.out.println(sb); // Output: Hello Java

4. delete(int start, int end)


 Purpose: Removes the characters in the substring from the start index to the end index.
 Syntax: sb.delete(start, end);
 Example:
StringBuffer sb = new StringBuffer("Hello World");

sb.delete(5, 11);

System.out.println(sb); // Output: Hello


5. deleteCharAt(int index)
 Purpose: Removes the character at the specified position in the StringBuffer.
 Syntax: sb.deleteCharAt(index);
 Example:
StringBuffer sb = new StringBuffer("Hello");

sb.deleteCharAt(4);

System.out.println(sb); // Output: Hell

6. reverse()
 Purpose: Reverses the sequence of characters in the StringBuffer.
 Syntax: sb.reverse();
 Example:
StringBuffer sb = new StringBuffer("Hello");

sb.reverse();

System.out.println(sb); // Output: olleH

7. setCharAt(int index, char ch)


 Purpose: Sets the character at the specified index to the given character.
 Syntax: sb.setCharAt(index, ch);
 Example:
StringBuffer sb = new StringBuffer("Hello");

sb.setCharAt(1, 'a');

System.out.println(sb); // Output: Hallo

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)

10. ensureCapacity(int minimumCapacity)


 Purpose: Ensures that the StringBuffer has at least the specified capacity.
 Syntax: sb.ensureCapacity(minimumCapacity);
 Example:
StringBuffer sb = new StringBuffer();

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

12. substring(int start) and substring(int start, int end)


 Purpose: Returns a new string that contains a subsequence of characters currently contained
in the StringBuffer. The substring begins at the specified index and extends to the end or
specified end index.
 Syntax:
 String subStr = sb.substring(start);
 String subStr = sb.substring(start, end);
 Example:
StringBuffer sb = new StringBuffer("Hello World");

String subStr = sb.substring(6);

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

Servlet Defines methods that all servlets must implement.

ServletRequest Defines an object to provide client request information to a servlet.

ServletResponse Defines an object to assist a servlet in sending a response to the client.

A servlet configuration object used by a servlet container to pass information to a servlet


ServletConfig
during initialization.

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

GenericServlet Defines a generic, protocol-independent servlet.

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.

Defines an exception that a servlet or filter throws to indicate that it is permanently or


UnavailableException
temporarily unavailable.

7.B] Explain how to read servlet parameters with an example


Answer:
In a servlet, parameters are often sent from the client (e.g., via an HTML form) and
can be accessed using the HttpServletRequest object. Parameters can be accessed in a
variety of ways, depending on whether they are query parameters, form parameters,
or parameters from a URL.
Here’s a breakdown of how to read servlet parameters:
1. Query Parameters
 Purpose: Parameters included in the URL after the ? (query string). Example
URL: http://example.com/servlet?param1=value1&param2=value2.
 Method to Use: getParameter(String name)
 Example Code:
import javax.servlet.*;

import javax.servlet.http.*;

import java.io.IOException;
public class QueryParamServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,


IOException {

// Retrieve query parameters

String param1 = req.getParameter("param1");

String param2 = req.getParameter("param2");

// Set content type and write response

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<html><body>");

out.println("<h1>Query Parameters</h1>");

out.println("<p>param1: " + param1 + "</p>");

out.println("<p>param2: " + param2 + "</p>");

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>

<input type="text" id="name" name="name">

<label for="age">Age:</label>

<input type="text" id="age" name="age">

<input type="submit" value="Submit">

</form>
 Example Servlet Code:
import javax.servlet.*;

import javax.servlet.http.*;

import java.io.IOException;

public class FormParamServlet extends HttpServlet {

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException {

// Retrieve form parameters

String name = req.getParameter("name");

String age = req.getParameter("age");

// Set content type and write response

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<html><body>");

out.println("<h1>Form Parameters</h1>");

out.println("<p>Name: " + name + "</p>");

out.println("<p>Age: " + age + "</p>");

out.println("</body></html>");

3. URL Path Parameters


 Purpose: Parameters included in the URL path, typically used with URL rewriting or RESTful
web services.
 Method to Use: getPathInfo(), getServletPath()
 Example URL: http://example.com/servlet/path/to/resource
 Example Servlet Code:
import javax.servlet.*;

import javax.servlet.http.*;
import java.io.IOException;

public class PathParamServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,


IOException {

// Retrieve path info

String pathInfo = req.getPathInfo();

// Set content type and write response

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<html><body>");

out.println("<h1>Path Parameters</h1>");

out.println("<p>Path Info: " + pathInfo + "</p>");

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&param2=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>

<!-- Form to handle GET requests -->

<h2>GET Request</h2>

<form method="get" action="getServlet">

Name: <input type="text" name="name">

<input type="submit" value="Submit">

</form>

<!-- Form to handle POST requests -->

<h2>POST Request</h2>

<form method="post" action="postServlet">

Name: <input type="text" name="name">

<input type="submit" value="Submit">

</form>

</body>

</html>

2. Handling GET Requests in a Servlet


import javax.servlet.*;

import javax.servlet.http.*;

import java.io.IOException;

import java.io.PrintWriter;
public class GetServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Set content type

response.setContentType("text/html");

// Get the PrintWriter to write the response

PrintWriter out = response.getWriter();

// Retrieve parameters from the request

String name = request.getParameter("name");

// Generate response

out.println("<html><body>");

out.println("<h2>GET Request</h2>");

out.println("<p>Hello, " + name + "!</p>");

out.println("</body></html>");

// Close the PrintWriter

out.close();

3. Handling POST Requests in a Servlet


import javax.servlet.*;

import javax.servlet.http.*;

import java.io.IOException;

import java.io.PrintWriter;

public class PostServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

// Set content type

response.setContentType("text/html");

// Get the PrintWriter to write the response

PrintWriter out = response.getWriter();

// Retrieve parameters from the request

String name = request.getParameter("name");

// Generate response

out.println("<html><body>");

out.println("<h2>POST Request</h2>");

out.println("<p>Hello, " + name + "!</p>");

out.println("</body></html>");

// Close the PrintWriter

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.

Limited by URL length restrictions (typically


Data Length No practical limits on data size.
around 2048 characters).

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.

8.B] Write a note on:


i) Session Tracking
ii) Cookies
Answer:
i) Session Tracking
 Session simply means a particular interval of time.
 Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
 Http protocol is a stateless so we need to maintain state using session tracking techniques.
 Each time user requests to the server, server treats the request as the new request.
 So we need to maintain the state of an user to recognize to particular user.
There are 2 techniques used in Session tracking:
 Cookies
 HttpSession
ii) Cookies
A cookie is a small piece of information that is persisted between the multiple client
requests.
By default, each request is considered as a new request.
In cookies technique, we add cookie with response from the servlet. So cookie is
stored in the cache of the browser. After that if request is sent by the user, cookie is
added with request by default. Thus, we recognize the user as the old user.

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

9.A] Explain the four types of JDBC drivers


Answer:
Java Database Connectivity(JDBC) is an Application Programming Interface(API) used
to connect Java application with Database.

 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:-

5 Steps to connect to the database in java


There are 5 steps to connect any java application with the database in java using
JDBC. They are as follows:
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
1. Register the Driver Class
 Purpose: Load the JDBC driver to connect to the database.
 Method: Class.forName("driverClassName")
Class.forName("com.mysql.cj.jdbc.Driver"); // Example for MySQL

2. Create the Connection Object


 Purpose: Establish a connection to the database.
 Method: DriverManager.getConnection(url, user, password)
String url = "jdbc:mysql://localhost:3306/mydatabase";

String user = "username";

String password = "password";

Connection con = DriverManager.getConnection(url, user, password);

3. Create & Execute Query


 Purpose: Create a statement and execute SQL queries.
 Methods: createStatement() and executeQuery()
Statement st = con.createStatement();

String sql = "SELECT id, name FROM users";

ResultSet rs = st.executeQuery(sql);

4. Process Data Returned from DBMS


 Purpose: Iterate through the ResultSet to process the retrieved data.
 Method: rs.next()
while (rs.next()) {

int id = rs.getInt(1); // Retrieve the first column

String name = rs.getString(2); // Retrieve the second column

System.out.println(id + " " + name);

}
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();

10.A] Write a Java program to execute a database transaction.


Answer:
 A transaction is a set of actions to be carried out as a single, atomic action. Either all
of the actions are carried out, or none of them are.
 Advantage is fast performance It makes the performance fast because database is hit
at the time of commit.

10.B] Explain Callable statement object with an example program.


Answer:
The CallableStatement interface is used to call stored procedures and functions in a
database. Here’s a detailed explanation with the provided snippet and an example.
Explanation
 Purpose:
 Call stored procedures or functions from Java.
 Set input parameters and retrieve output parameters.
Code Snippet Explanation
1. Prepare the CallableStatement:
String SQL = "{call getEmpName (?, ?)}"; // Stored procedure call

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.

You might also like