VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
MANGALORE UNIVERSITY
VI Semester BCA
Advanced Java and J2EE
Question Bank with Answers
Based on Herbert Schildt: Java The Complete Reference
& Jim Keogh: J2EE The Complete Reference
Compiled by
Vadiraja Bhat
Page 1 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
UNIT 1: Enumerations, Autoboxing, Annotations and Java
Beans
Section A: Short Answer Questions (2 Marks)
Q1. With the syntax write the purpose of ordinal() method.
The ordinal() method returns the ordinal value (position) of an enumeration constant, which
represents the order in which the constant was declared, starting from zero.
Syntax:
final int ordinal()
Example: For enum Day { MON, TUE, WED }, [Link]() returns 0, [Link]()
returns 1.
Q2. List two key characteristics of enumeration constants in Java.
• Each enumeration constant is implicitly public, static, and final, making it a constant that
cannot be changed.
• Enumeration constants are objects of the enumeration type itself (since Java enumerations
are class types), so they can have fields, constructors, and methods.
Q3. What is an enumeration? How can an enumeration be created?
An enumeration (enum) is a list of named constants that define a new data type. It provides a
way to create groups of related constants with type safety.
An enumeration is created using the enum keyword:
enum EnumName { CONST1, CONST2, CONST3 }
Example: enum Apple { Jonathan, GoldenDel, RedDel, Winesap }
Q4. Differentiate values() and valueOf() methods in Java enumerations.
• values(): Returns an array containing all the enumeration constants in the order they are
declared. Syntax: EnumType[] values()
• valueOf(): Returns the enumeration constant whose value corresponds to the string passed
as argument. Syntax: EnumType valueOf(String str)
Q5. Provide an example of how to use the values() method to iterate through all
constants in an enumeration.
enum Apple { Jonathan, GoldenDel, RedDel }
Apple allapples[] = [Link]();
for(Apple a : allapples)
[Link](a);
This prints: Jonathan, GoldenDel, RedDel on separate lines.
Page 2 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Q6. Give the functionalities of compareTo() and equals() methods in Java
enumerations.
• compareTo(): Compares two enumeration constants based on their ordinal values. Returns
a negative value if the calling constant comes before, zero if same, positive if it comes after
the argument.
• equals(): Returns true if the calling constant is equal to the argument constant. It compares
object identity of the enum constants.
Q7. Why are type wrappers used in Java?
• Primitive types (int, double, etc.) are not objects, but many Java features (like Collections)
require objects. Type wrappers (Integer, Double, etc.) wrap primitives as objects.
• They provide useful methods for converting between types, parsing strings, and performing
operations (e.g., [Link](), [Link]()).
Q8. What is the purpose of the doubleValue() method in a numeric wrapper class?
The doubleValue() method returns the value of a numeric wrapper object as a double primitive
type. It is defined in the abstract Number class and overridden in all numeric wrapper classes.
Syntax: double doubleValue()
Example: Integer iOb = new Integer(100); double d = [Link](); // d = 100.0
Q9. What is the benefit of autoboxing and auto-unboxing in Java?
• Autoboxing: Automatically converts a primitive type to its corresponding wrapper object
(e.g., int to Integer), eliminating the need for manual wrapping.
• Auto-unboxing: Automatically converts a wrapper object back to its primitive type (e.g.,
Integer to int), making code cleaner, shorter, and reducing the chance of errors.
Q10. What is retention policy? How to set retention policy? Give an example.
A retention policy determines at what point an annotation is discarded. It is specified using
@Retention annotation with RetentionPolicy enum.
The three policies are: SOURCE (discarded by compiler), CLASS (stored in .class file but not
available at runtime), RUNTIME (available at runtime via reflection).
Syntax:
@Retention([Link])
@interface MyAnno { String str(); int val(); }
Q11. List any two retention policies with their purpose.
• [Link]: The annotation is retained at runtime, making it available via
reflection. Used when annotations need to be inspected during program execution.
• [Link]: The annotation is available only in the source code and is
discarded by the compiler. Used for documentation or compiler hints only.
Q12. What is the purpose of setting default values to annotation members? Write
the general form.
Page 3 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Default values allow annotation members to have predefined values, so they need not be
specified every time the annotation is applied. This makes annotations more flexible and
reduces redundant code.
General Form:
type member() default value;
Example: String str() default "Testing"; — if str is not provided, it defaults to "Testing".
Q13. Define: a) Marker Annotation b) Single Member Annotation
a) Marker Annotation: An annotation that has no members. It simply marks a declaration for
some purpose. Example: @interface MyMarker { }
b) Single Member Annotation: An annotation that contains only one member named value().
When applied, only the value needs to be specified without naming the member. Example:
@interface MySingle { int value(); }
Q14. List any two built-in annotations with their purpose.
• @Override: Tells the compiler that the annotated method overrides a method in the
superclass. Generates an error if the method does not actually override.
• @Deprecated: Marks a method or class as deprecated (outdated). The compiler issues a
warning when deprecated elements are used.
Q15. Write any two restrictions on annotations.
• Annotations cannot extend other annotations or classes. All annotations implicitly extend
the [Link] interface.
• Annotation members cannot have parameters, and they cannot throw exceptions. The type
of a member must be a primitive, String, Class, enum, another annotation, or an array of
these.
Q16. What is the primary purpose of annotations in Java code?
Annotations (metadata) provide additional information about a program element to the
compiler, development tools, or runtime environment without directly affecting the program's
execution logic.
They can be used to suppress warnings, indicate method overrides, mark deprecated code, or
carry custom information processed by frameworks and tools.
Q17. How are annotations declared in Java? Give an example.
Annotations are declared using the @interface keyword, similar to an interface declaration.
@interface MyAnno {
String str();
int val();
}
Each method declaration defines a member of the annotation. No bodies are provided for the
methods.
Page 4 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Q18. How can you retrieve all annotations with the RUNTIME retention policy? Give
its syntax.
The getAnnotations() method of the AnnotatedElement interface retrieves all annotations with
RUNTIME retention associated with an element.
Annotation[] getAnnotations()
Example: Annotation[] annots = [Link]().getMethod("myMeth").getAnnotations();
Q19. Name any two commonly used built-in annotations and briefly describe their
purpose.
• @SuppressWarnings: Instructs the compiler to suppress specific warnings (e.g., unchecked
casts). Example: @SuppressWarnings("unchecked")
• @FunctionalInterface: Indicates that the annotated interface is a functional interface (has
exactly one abstract method). Introduced in JDK 8.
Q20. What are some key characteristics of a Java Bean?
• A JavaBean is a reusable software component that has properties, events, and methods
that can be manipulated by a visual builder tool.
• It must be serializable, have a public no-argument constructor, and follow naming
conventions for getter/setter methods (getProperty()/setProperty()).
Q21. List two advantages of Java Beans.
• Reusability: JavaBeans can be reused across different applications and can be plugged
into different environments without modification.
• Visual Development: JavaBeans are designed to work with visual builder tools (like IDEs),
allowing developers to assemble components graphically without writing extensive code.
Q22. Why is introspection essential for Java Beans technology?
Introspection allows tools and containers to discover the properties, events, and methods of a
JavaBean at runtime, without access to source code.
This enables visual builder tools to let developers configure beans and wire them together. It is
done either via design patterns (naming conventions) or BeanInfo class.
Q23. What is the difference between a simple property and an indexed property?
• Simple Property: Represents a single value of any data type. It has one getter (getX()) and
one setter (setX()) method.
• Indexed Property: Represents an array of values. It provides methods to access individual
elements by index (getX(int i), setX(int i, T val)) as well as the entire array.
Q24. What are the two main components used to define a simple property in a Java
Bean?
• Getter Method (getPropertyName()): Returns the current value of the property. For boolean
properties, isPropertyName() is used.
Page 5 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• Setter Method (setPropertyName(value)): Sets/modifies the value of the property.
Q25. Key differences between bound properties and constrained properties.
• Bound Property: Generates a PropertyChangeEvent whenever its value changes.
Interested listeners register via addPropertyChangeListener() to receive notification after
the change.
• Constrained Property: Also generates events on change, but listeners can veto (reject) the
change by throwing a PropertyVetoException. Listeners register via
addVetoableChangeListener().
Q26. What is persistence in JavaBeans?
Persistence in JavaBeans refers to the ability of a bean to save its state (properties and
configuration) to a storage medium and restore it later.
JavaBeans support persistence through Java Serialization — a bean implementing Serializable
interface can be serialized to a stream and deserialized when needed.
Q27. What are customizers?
Customizers are specialized GUI editors provided by a bean that allow users to configure
complex properties in a customized, user-friendly way.
Instead of relying on the default property sheet, a customizer provides a custom dialog or
wizard to guide a developer through setting up the bean's properties in a builder tool.
Section B: Long Answer Questions (4–6 Marks)
Q1. With an example explain how enumeration values are used to control a switch
statement.
In Java, enumeration constants can be used directly in switch statements. The switch
expression is of the enum type, and each case uses an enum constant (without the type prefix
inside the case).
Example:
enum Apple { Jonathan, GoldenDel, RedDel, Winesap }
Apple ap = [Link];
switch(ap) {
case Jonathan:
[Link]("Jonathan is red."); break;
case GoldenDel:
[Link]("Golden Delicious is yellow."); break;
case RedDel:
[Link]("Red Delicious is red."); break;
case Winesap:
[Link]("Winesap is red."); break;
}
Key points:
• The switch expression uses the enum variable directly.
Page 6 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• In case labels, only the constant name is used (e.g., Jonathan, not [Link]).
• Using enum in switch provides type safety — invalid constants are caught at compile time.
• This is cleaner and safer than using integer constants.
Q2. Demonstrate the usage of the valueOf() and values() methods with an example.
values(): Returns an array of all constants in the enum type in the order declared.
valueOf(): Returns the enum constant that matches the given string.
enum Apple { Jonathan, GoldenDel, RedDel, Winesap }
// Using values()
Apple[] allapples = [Link]();
for(Apple a : allapples)
[Link](a + " ordinal: " + [Link]());
// Output: Jonathan ordinal:0, GoldenDel ordinal:1, ...
// Using valueOf()
Apple ap = [Link]("Winesap");
[Link](ap); // Output: Winesap
Key points:
• values() is useful for iterating over all constants with a for-each loop.
• valueOf() is useful when you receive a string (e.g., from user input) and want to convert it to
an enum constant.
• valueOf() throws IllegalArgumentException if the string does not match any constant.
Q3. What does ordinal(), compareTo() and equals() do in Enum? Give an example.
ordinal(): Returns the zero-based position of the constant as declared in the enum.
compareTo(): Compares two enum constants by their ordinal value. Returns negative, zero, or
positive.
equals(): Returns true if the calling constant is the same as the argument.
enum Apple { Jonathan, GoldenDel, RedDel }
Apple a1 = [Link];
Apple a2 = [Link];
[Link]([Link]()); // 1
[Link]([Link](a2)); // negative (1-2 = -1)
[Link]([Link](a2)); // false
[Link]([Link]([Link])); // true
Q4. Java Enumerations Are Class Types. Explain with an example.
In Java, each enum is actually a class that implicitly extends [Link]. This means:
• Enum can have constructors, instance variables, and methods.
• Each enum constant is actually an object of the enum type.
• The constructor is called for each constant when the enum is loaded.
• Enum cannot be instantiated with new; constants are the only instances.
enum Apple {
Jonathan(10), GoldenDel(9), RedDel(12), Winesap(15);
private int price;
Apple(int p) { price = p; }
int getPrice() { return price; }
}
Page 7 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
// Usage:
[Link]([Link]()); // 10
Here, each constant has an associated price, demonstrating that enumerations are full-fledged
class types.
Q5. Explain with example how Enumerations can Inherit Enum.
All enumerations in Java automatically inherit the [Link] class. This gives every enum
access to the following predefined methods:
• ordinal(): Returns the position of the constant.
• compareTo(): Compares two constants by ordinal.
• equals(): Checks equality of two constants.
• toString(): Returns the name of the constant as a string.
• name(): Returns the exact declared name of the constant.
enum Direction { NORTH, SOUTH, EAST, WEST }
Direction d = [Link];
[Link]([Link]()); // NORTH
[Link]([Link]()); // 0
Since all enums inherit Enum, they cannot extend any other class (Java does not support
multiple inheritance). However, they can implement interfaces.
Q6. Describe the Wrapper classes available for primitive types.
Java provides a wrapper class for each primitive type to allow primitives to be used as objects:
• byte → Byte
• short → Short
• int → Integer
• long → Long
• float → Float
• double → Double
• char → Character
• boolean → Boolean
Key features of wrapper classes:
• They encapsulate a primitive value inside an object.
• They provide conversion methods like parseInt(), doubleValue(), toString().
• Numeric wrappers extend the abstract Number class and implement Comparable.
• They define constants like MAX_VALUE, MIN_VALUE for numeric types.
Q7. What Is Autoboxing And Unboxing? Explain with an example.
Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class
object by the Java compiler.
Unboxing is the automatic conversion of a wrapper object back to its corresponding primitive
type.
// Autoboxing: int → Integer
Integer iOb = 100; // compiler converts int 100 to Integer
// Auto-unboxing: Integer → int
int i = iOb; // compiler extracts int from Integer
// Autoboxing in expressions
Page 8 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Integer a = 10, b = 20;
int sum = a + b; // both unboxed, added, result is int
Benefits:
• Eliminates the need for manual wrapping/unwrapping code.
• Makes collections work seamlessly with primitives.
• Reduces risk of errors from incorrect manual conversions.
Q8. With an example explain the steps involved to obtain annotation at run time
using reflection.
To obtain an annotation at runtime, the annotation must have RUNTIME retention. Steps:
• Step 1: Define the annotation with @Retention([Link]).
• Step 2: Apply the annotation to a method or class.
• Step 3: Use reflection to get the Method or Class object.
• Step 4: Call getAnnotation() on the Method/Class object.
• Step 5: Access the annotation's members.
@Retention([Link])
@interface MyAnno { String str(); int val(); }
class Meta {
@MyAnno(str="Two parameters", val=19)
public static void myMeth() { }
}
Method m = [Link]("myMeth");
MyAnno anno = [Link]([Link]);
[Link]([Link]()); // Two parameters
[Link]([Link]()); // 19
Q9. What Are Annotations? What are the three retention policies?
Annotations are a form of metadata added to Java source code. They provide information to
the compiler, tools, or runtime without directly affecting program logic. Declared using
@interface keyword.
The three retention policies defined by RetentionPolicy enumeration:
• [Link]: Annotation is retained only in source code. It is discarded by the
compiler and not present in .class files. Used for source-level processing tools.
• [Link]: Annotation is recorded in the .class file by the compiler but not
available at runtime via JVM. This is the default retention policy.
• [Link]: Annotation is recorded in .class file and is available at runtime
via reflection. Most useful for frameworks and tools that inspect code at runtime.
Q10. Write an example program to illustrate reflection.
Reflection allows a program to obtain information about a class, method, or field at runtime.
import [Link].*;
class MyClass {
public int x;
public void display() { [Link]("Hello"); }
}
public class ReflectDemo {
public static void main(String[] args) throws Exception {
Page 9 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Class c = [Link];
[Link]("Class: " + [Link]());
Method[] methods = [Link]();
for(Method m : methods)
[Link]("Method: " + [Link]());
Field[] fields = [Link]();
for(Field f : fields)
[Link]("Field: " + [Link]());
}
}
Output will display class name, method names (display, etc.) and field name (x).
Q11. Explain any four Built-in annotations.
• @Override: Tells the compiler that the annotated method overrides a superclass method. If
the method doesn't override, a compile-time error is generated. Prevents subtle bugs.
• @Deprecated: Marks a method, class, or field as obsolete/outdated. The compiler issues a
warning when the deprecated element is used. Encourages migration to newer alternatives.
• @SuppressWarnings: Instructs the compiler to suppress specific types of warnings for the
annotated element. Example: @SuppressWarnings("unchecked") suppresses unchecked
cast warnings.
• @FunctionalInterface (JDK 8+): Indicates that the annotated interface is a functional
interface — it has exactly one abstract method. Generates an error if the interface is not
functional.
Q12. How do you specify a default value for an annotation member? Explain with
example.
Default values are specified using the default keyword after the member type declaration.
When the annotation is applied without specifying a value for that member, the default is used.
@Retention([Link])
@interface MyAnno {
String str() default "Testing";
int val() default 9000;
}
// Using all defaults:
@MyAnno() // str="Testing", val=9000
// Overriding one:
@MyAnno(str="Hello") // val still=9000
Default values make annotations more convenient since developers don't need to specify every
member each time.
Q13. Write an example of defining a marker annotation.
A marker annotation has no members. It simply marks a declaration for special processing.
@Retention([Link])
@interface MyMarker { } // no members
// Application of marker annotation:
@MyMarker
public static void myMeth() { ... }
// Checking if marker annotation is present:
Page 10 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Method m = [Link]("myMeth");
if([Link]([Link]))
[Link]("MyMarker is present");
Q14. Write an example of defining a single-member annotation.
A single-member annotation has exactly one member named value(). When applying it, you
can specify just the value without the member name.
@Retention([Link])
@interface MySingle { int value(); }
// Application (shorthand — no need to write value=):
@MySingle(100)
public static void myMeth() { ... }
// Retrieving:
MySingle anno = [Link]([Link]);
[Link]([Link]()); // 100
Q15. How Can You Retrieve all Annotations that have RUNTIME retention by use of
reflection?
The getAnnotations() method returns an array of all RUNTIME annotations present on a class,
method, or field. Steps:
• Step 1: Get the Method (or Class/Field) object via reflection.
• Step 2: Call getAnnotations() on the object — returns Annotation[].
• Step 3: Iterate over the array and process each annotation.
Method m = [Link]("myMeth");
Annotation[] annots = [Link]();
for(Annotation a : annots) {
[Link](a);
}
Only annotations with @Retention([Link]) are returned. SOURCE and
CLASS annotations are not visible at runtime.
Q16. Discuss the key advantages that Java Beans provide to component
developers.
• Reusability: Beans can be plugged into different applications without modification, reducing
development time.
• Visual Development: Beans work with builder tools, enabling drag-and-drop GUI assembly
and property configuration.
• Introspection: Builder tools can inspect a bean's properties, methods, and events
automatically, enabling seamless integration.
• Event Handling: The bean event model allows beans to communicate with each other
through a well-defined listener/event mechanism.
• Persistence: Beans can save and restore their state, making configuration persistent across
sessions.
Q17. What are the different properties of a Java Bean? Explain with examples.
Page 11 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• Simple Property: A single value with getter/setter. Example: private int size; public int
getSize(){ return size; } public void setSize(int s){ size=s; }
• Indexed Property: Array-based. Provides getters/setters for both array and individual
elements. Example: getDataPoint(int i), setDataPoint(int i, double val).
• Bound Property: Fires a PropertyChangeEvent when changed. Uses
PropertyChangeSupport to notify listeners. Example: setX() notifies all registered
PropertyChangeListeners.
• Constrained Property: Listeners can veto changes by throwing PropertyVetoException.
Uses VetoableChangeSupport. Example: setAge() can be vetoed if age is invalid.
Q18. Write short note on: i) Bound and Constrained properties ii) Persistence
i) Bound and Constrained Properties:
Bound Property: When a bound property's value changes, all registered
PropertyChangeListeners are notified via a PropertyChangeEvent. The bean uses
PropertyChangeSupport to fire events.
Constrained Property: Similar to bound, but listeners registered via
addVetoableChangeListener() can reject the change by throwing PropertyVetoException. The
change is only made if no listener vetoes it.
ii) Persistence:
Persistence allows a bean to save its current state to persistent storage and restore it later. In
Java, this is achieved by implementing the Serializable interface. When a bean is serialized, all
its properties are saved. This is critical in visual builder tools where a bean's configuration must
survive across application restarts.
Q19. Write a note on simple properties in Java Beans.
A simple property represents a single value associated with a bean. It follows the JavaBeans
naming convention:
• Getter method: public T getPropertyName() — returns the property value.
• Setter method: public void setPropertyName(T value) — sets the property value.
• For boolean: public boolean isPropertyName() can replace the getter.
Example:
private double balance;
public double getBalance() { return balance; }
public void setBalance(double b) { balance = b; }
Builder tools discover simple properties via introspection by looking for these naming patterns.
Simple properties are the most basic and commonly used property type in JavaBeans.
Q20. Write a note on indexed properties in Java Beans.
An indexed property represents an array of values associated with a bean. It has four accessor
methods:
// Get/set entire array:
public T[] getPropertyName()
public void setPropertyName(T[] values)
// Get/set single element:
public T getPropertyName(int index)
public void setPropertyName(int index, T value)
Example:
Page 12 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
private double[] dataSet;
public double getDataSet(int i) { return dataSet[i]; }
public void setDataSet(int i, double v) { dataSet[i] = v; }
Builder tools recognise indexed properties through introspection and may present them as
array editors.
Q21. What are the steps to be followed in creating a new Bean?
• Step 1: Write the Java class following JavaBeans conventions — public class, no-argument
constructor, implement Serializable.
• Step 2: Define private instance variables for properties.
• Step 3: Provide public getter and setter methods following the getXxx()/setXxx() naming
convention.
• Step 4: Add event support if required — use PropertyChangeSupport for bound properties
or VetoableChangeSupport for constrained properties.
• Step 5: Compile the class and package it into a JAR file (with a manifest that identifies the
bean).
• Step 6: Load the bean into a builder tool for testing and integration.
Q22. Explain the purpose and usage of Introspector, PropertyDescriptor,
EventSetDescriptor, and MethodDescriptor classes.
• Introspector: Provides static methods to examine a bean. getBeanInfo(Class c) returns a
BeanInfo object describing the bean's properties, events, and methods by analyzing
naming conventions.
• PropertyDescriptor: Describes a property of a bean. Provides getName() to get property
name, getReadMethod() and getWriteMethod() to get getter and setter Method objects.
• EventSetDescriptor: Describes a set of events fired by a bean. Provides getListenerType()
to get the event listener class and getAddListenerMethod()/getRemoveListenerMethod().
• MethodDescriptor: Describes a method exposed by a bean. Provides getMethod() to get
the actual Method object and getName() to get the method name.
Q23. Write a note on EventSetDescriptor and PropertyDescriptor class.
PropertyDescriptor: Part of the [Link] package. Describes a property of a JavaBean. Key
methods:
• getName(): Returns the property name.
• getReadMethod(): Returns the Method object for the getter.
• getWriteMethod(): Returns the Method object for the setter.
EventSetDescriptor: Describes a group of events that a bean fires. Key methods:
• getName(): Returns the name of the event set.
• getListenerType(): Returns the Class object for the listener interface.
• getAddListenerMethod(): Returns the method to add a listener.
• getRemoveListenerMethod(): Returns the method to remove a listener.
Page 13 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
UNIT 2: Collections Framework and MVC Architecture
Section A: Short Answer Questions (2 Marks)
The Collection Framework in Java is a set of classes and interfaces in the [Link] package that provides a unified
architecture for storing, manipulating, and processing groups of objects.
Q1. What is Collection Framework? List any two goals.
The Collections Framework is a unified architecture for representing and manipulating groups
of objects. It consists of interfaces, implementations (classes), and algorithms.
• Goal 1: High-performance and high-quality implementations of data structures (ArrayList,
LinkedList, TreeSet, etc.).
• Goal 2: Interoperability — collections can work together and pass data between different
types easily.
Q2. What are the benefits of using the Collections Framework?
• Reduces programming effort by providing ready-made data structures and algorithms (sort,
search, etc.) so developers don't need to write them from scratch.
• Increases performance and code quality through high-performance implementations and
promotes reuse and interoperability between unrelated APIs.
Q3. List any two collection classes with their purpose.
• ArrayList: A dynamic array that grows as needed. Provides fast random access (index-
based) to elements. Implements the List interface.
• HashSet: Stores elements using a hash table. Does not allow duplicates and does not
maintain insertion order. Implements the Set interface.
Q4. Write the differences between hasNext() and next() method.
• hasNext(): Returns true if there are more elements to iterate, false otherwise. Does not
advance the iterator or return any element.
• next(): Returns the next element in the collection and advances the iterator position.
Throws NoSuchElementException if there are no more elements.
Q5. What is Map? List any two Map interfaces.
A Map stores key/value pairs, where each key is unique and maps to exactly one value. Unlike
Collection, Map does not implement the Collection interface.
• Map: The basic interface for all map types. Defines operations like put(), get(), remove(),
containsKey().
• SortedMap: Extends Map and maintains keys in ascending sorted order. Provides methods
like firstKey(), lastKey(), headMap(), tailMap().
Q6. Write the purpose of the Arrays class.
Page 14 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
The Arrays class provides static utility methods for working with arrays. It includes methods for
sorting (sort()), searching (binarySearch()), filling (fill()), comparing (equals()), and copying
(copyOf()) arrays.
It bridges the gap between arrays and the collections framework via asList().
Q7. Write the purpose of fill() and copyOf().
• fill(): Assigns a specified value to every element in an array (or a range). Syntax:
[Link](array, value) or [Link](array, fromIndex, toIndex, value).
• copyOf(): Copies an array into a new array of the specified length. If the new length is
greater, the extra elements are filled with default values. Syntax: [Link](original,
newLength).
Q8. Write the usage of Iterator interface.
Iterator is used to traverse (iterate over) elements in a Collection one at a time, in a forward
direction. It provides:
• hasNext(): Returns true if more elements exist.
• next(): Returns the next element.
• remove(): Removes the last element returned by next() from the underlying collection.
Q9. List any four interfaces provided by the Collection Framework.
• Collection: The root interface. Defines basic operations like add(), remove(), contains(),
size().
• List: Ordered collection (sequence). Allows duplicate elements and index-based access.
• Set: Collection with no duplicate elements.
• Queue: Designed for holding elements prior to processing. Follows FIFO order typically.
Q10. Write any two uses of Generics.
• Type Safety: Generics enforce compile-time type checking in collections, preventing
ClassCastException at runtime. E.g., ArrayList<String> only accepts String objects.
• Code Reusability: Generic algorithms and classes work on any data type, reducing code
duplication. E.g., a single sort method works for Integer, String, etc.
Q11. List any four exceptions thrown in the context of collections.
• UnsupportedOperationException: Thrown when an optional operation (like add or remove)
is not supported by the collection.
• ClassCastException: Thrown when an object is incompatible with the elements in the
collection.
• NullPointerException: Thrown when a null element is added to a collection that does not
allow nulls.
• ConcurrentModificationException: Thrown when a collection is modified while being
iterated.
Q12. What is the usage of containsAll() and retainAll() methods?
Page 15 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• containsAll(Collection c): Returns true if the invoking collection contains all elements of the
collection c. Used to check subset relationship.
• retainAll(Collection c): Removes all elements from the invoking collection that are NOT in c
(intersection). Returns true if the collection changed.
Q13. List any four methods of List interface.
• add(int index, E obj): Inserts obj at the specified index.
• get(int index): Returns the element at the specified index.
• set(int index, E obj): Replaces the element at index with obj.
• remove(int index): Removes the element at the specified index.
Q14. What is the purpose of the NavigableSet interface?
NavigableSet extends SortedSet and provides navigation methods to find the closest matches
for given elements. It provides:
• lower(e): Returns the greatest element strictly less than e.
• higher(e): Returns the smallest element strictly greater than e.
• floor(e): Returns the greatest element ≤ e.
• ceiling(e): Returns the smallest element ≥ e.
Q15. How can you add or remove elements from the first/last using LinkedList
Class?
• Add to first: addFirst(E e) or offerFirst(E e) inserts an element at the beginning.
• Add to last: addLast(E e) or offerLast(E e) inserts an element at the end.
• Remove from first: removeFirst() or pollFirst() removes and returns the first element.
• Remove from last: removeLast() or pollLast() removes and returns the last element.
Q16. Differentiate headSet() and tailSet() methods.
• headSet(E toElement): Returns a view of the portion of the set whose elements are strictly
less than toElement.
• tailSet(E fromElement): Returns a view of the portion of the set whose elements are greater
than or equal to fromElement.
Q17. Differentiate poll() and remove() methods of Queue interface.
• poll(): Retrieves and removes the head of the queue. Returns null if the queue is empty —
does not throw an exception.
• remove(): Retrieves and removes the head of the queue. Throws
NoSuchElementException if the queue is empty.
Q18. List any four methods of Deque interface.
• push(E e): Pushes an element onto the stack represented by the deque (adds at front).
• pop(): Pops an element from the stack (removes from front).
• peekFirst(): Retrieves but does not remove the first element (returns null if empty).
Page 16 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• peekLast(): Retrieves but does not remove the last element (returns null if empty).
Q19. What is the purpose of push() and pop() methods of Deque interface?
• push(E e): Pushes an element onto the deque stack — equivalent to addFirst(). Places the
element at the front of the deque.
• pop(): Pops an element from the deque stack — equivalent to removeFirst(). Removes and
returns the front element. Throws NoSuchElementException if empty.
Q20. How does an ArrayList differ from standard arrays?
• Dynamic sizing: ArrayList grows or shrinks automatically as elements are added or
removed. Standard arrays have a fixed size once created.
• Object storage: ArrayList stores objects (uses autoboxing for primitives), provides many
utility methods like add(), remove(), contains(), and supports generics for type safety.
Q21. What are the two overloaded toArray() methods in ArrayList?
Object[] toArray()
Returns an array containing all elements of the ArrayList in order. The returned array is of type
Object[].
<T> T[] toArray(T[] array)
Returns an array containing all elements. If the specified array is large enough, elements are
stored there. Otherwise, a new array of the same type is allocated.
Q22. What is the difference between HashSet() and HashSet(int capacity)
constructors?
• HashSet(): Creates an empty hash set with default initial capacity (16) and default load
factor (0.75). Suitable for general use when size is unknown.
• HashSet(int capacity): Creates an empty hash set with the specified initial capacity and
default load factor (0.75). Use when the approximate number of elements is known to avoid
rehashing.
Q23. What is the purpose of the float fillRatio in HashSet constructor?
The fill ratio (also called load factor) determines how full the hash set can be before it is resized
(rehashed). It ranges from 0.0 to 1.0.
A value of 0.75 means: when 75% of the capacity is filled, the set is resized. Lower values
reduce collision probability but increase memory usage. Higher values save space but increase
collision and lookup time.
Q24. Primary advantage of TreeSet over HashSet?
• TreeSet stores elements in sorted ascending order (natural ordering or custom
Comparator), making it ideal when sorted traversal is needed.
• It also provides efficient navigation methods (first(), last(), headSet(), tailSet(), floor(),
ceiling()) which are not available in HashSet. The trade-off is slightly slower O(log n)
operations vs O(1) for HashSet.
Page 17 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Q25. Main difference between for-each loop and Iterator to traverse a Collection?
• For-each loop: Simpler, more readable syntax. Does not allow removal of elements during
traversal. Cannot traverse in reverse. Behind the scenes, it uses an Iterator.
• Iterator: More explicit. Allows removing elements during traversal using remove(). Provides
more control. ListIterator (for List) also allows traversal in both directions.
Q26. What is the purpose of the RandomAccess interface?
RandomAccess is a marker interface (no methods) that signals that a List implementation
supports fast random (index-based) access, typically in O(1) time.
Algorithms can check if(list instanceof RandomAccess) to choose the most efficient traversal
strategy — index-based loop for RandomAccess lists (ArrayList), iterator-based for others
(LinkedList).
Q27. How does a Map differ from a Collection in Java?
• A Map stores key-value pairs, where each key is unique and maps to a value. You access
elements by key, not by index or iterator directly.
• A Collection stores individual elements. Map does not extend or implement the Collection
interface; it is a separate hierarchy in the Collections Framework.
Q28. List any four Map classes.
• HashMap: Stores key-value pairs using a hash table. Allows one null key, does not
maintain order.
• TreeMap: Stores keys in sorted ascending order. Implements NavigableMap.
• LinkedHashMap: Maintains insertion order of entries. Extends HashMap.
• Hashtable: Legacy synchronized map class. Does not allow null keys or values.
Q29. What is the purpose of using a Comparator with TreeSet and TreeMap?
By default, TreeSet and TreeMap use the natural ordering (Comparable interface) to sort
elements. A Comparator allows custom sorting logic without modifying the element class.
Example: You can use a Comparator to sort strings by length, sort in reverse order, or sort
user-defined objects by any field.
Q30. List any four overloaded forms of binarySearch() method.
static int binarySearch(byte[] a, byte key)
static int binarySearch(int[] a, int key)
static int binarySearch(Object[] a, Object key)
static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
Returns the index of the key if found, or a negative value if not. Array must be sorted before
calling.
Q31. Differentiate Vector and Arrays.
Page 18 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• Vector: A dynamic, resizable collection that can grow or shrink. It is synchronized (thread-
safe). Stores objects. Part of [Link] package and implements List.
• Arrays: Static data structure with fixed size determined at creation. Direct access by index.
Can store primitives and objects. Not synchronized. Arrays class provides utility methods.
Q32. What is the relationship between the Dictionary class and the Map interface?
Dictionary is a legacy abstract class (Java 1.0 era) that defined key/value storage, similar in
concept to Map. Hashtable extended Dictionary.
The Map interface was introduced later as part of the Collections Framework and is the modern
replacement. Dictionary is considered obsolete; all new code should use Map implementations.
Q33. Two advantages of MVC architecture.
• Separation of Concerns: Model, View, and Controller are independent, making the code
easier to manage, test, and maintain. Changes in UI do not affect business logic.
• Multiple Views: The same model data can be presented through multiple views (web,
mobile, desktop) without changing the model or controller.
Q34. What is Model-View-Controller (MVC)?
MVC is a software architectural pattern that divides an application into three interconnected
components:
• Model: Represents the data and business logic. Manages data, responds to queries, and
notifies the view of changes.
• View: Presents data to the user (UI layer). Receives data from the model and renders it.
• Controller: Acts as an intermediary. Receives user input, interacts with the model, and
determines which view to display.
Q35. Two responsibilities of the View component in MVC.
• Presentation: Renders the model data in a user-friendly format (HTML page, GUI form,
chart, etc.).
• User Interface: Provides the interface through which users interact with the system
(buttons, forms, links) and forwards user input to the Controller.
Q36. Primary roles of the Controller component in MVC.
• Input Handling: Receives and processes user input (HTTP requests, button clicks, etc.).
• Orchestration: Invokes the appropriate model operations and selects the appropriate view
to render the response.
Q37. Responsibilities of the Model component.
• Data Management: Stores, retrieves, and manages application data. Communicates with
the database or data source.
• Business Logic: Implements the core logic and rules of the application. Notifies the view of
data changes (using observer pattern in some implementations).
Page 19 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Section B: Long Answer Questions (4–6 Marks)
Q1. Explain the benefits of Generics in the Collections Framework.
• Type Safety at Compile Time: Generics enforce type checking during compilation. Adding a
wrong type to a generic collection (e.g., ArrayList<String>) produces a compile error,
preventing ClassCastException at runtime.
• Elimination of Casts: Without generics, every retrieval from a collection requires an explicit
cast: (String) [Link](0). With generics, the cast is automatic and safe.
• Code Reusability: A single generic class or method works with any type, reducing code
duplication. Example: [Link]() works for any List of Comparable elements.
• Better Readability: Generic declarations clearly document the intended type, making code
easier to understand. ArrayList<Student> is self-documenting.
• Interoperability: Generic collections work seamlessly with autoboxing, allowing primitives to
be stored and retrieved without manual wrapping.
Q2. List any five methods of Collection interface with their purpose.
• add(E obj): Adds obj to the collection. Returns true if obj was added, false if already present
(for sets).
• remove(Object obj): Removes one occurrence of obj. Returns true if the element was found
and removed.
• contains(Object obj): Returns true if the collection contains obj.
• size(): Returns the number of elements currently in the collection.
• iterator(): Returns an Iterator that can be used to traverse the elements of the collection one
by one.
Q3. What are the basic interfaces of Java Collections Framework? Discuss the
appropriate use of any four.
The core interfaces are: Collection, List, Set, SortedSet, NavigableSet, Queue, Deque, Map,
SortedMap, NavigableMap.
• Collection: Root interface. Use when you need a generic container without specific ordering
or access rules. Contains basic add/remove/contains operations.
• List: Use when order matters and duplicates are allowed. Supports index-based access.
Implemented by ArrayList (fast random access) and LinkedList (fast insertions/deletions).
• Set: Use when uniqueness is required. No duplicate elements. Implemented by HashSet
(fast, unordered) and TreeSet (sorted).
• Queue: Use for FIFO processing. Ideal for task queues, scheduling. Implemented by
LinkedList and PriorityQueue. Methods: offer(), poll(), peek().
Q4. List any five methods of List interface with their purpose.
• add(int index, E obj): Inserts obj at the specified index, shifting subsequent elements right.
• get(int index): Returns the element at the specified index. Provides random access.
• set(int index, E obj): Replaces element at index with obj. Returns the old element.
• remove(int index): Removes the element at the specified position. Returns the removed
element.
Page 20 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• indexOf(Object obj): Returns the index of the first occurrence of obj in the list, or -1 if not
found.
Q5. Explain any four methods defined by NavigableSet interface.
• lower(E e): Returns the greatest element strictly less than e, or null if no such element.
• higher(E e): Returns the smallest element strictly greater than e, or null if no such element.
• floor(E e): Returns the greatest element less than or equal to e, or null if no such element.
• ceiling(E e): Returns the smallest element greater than or equal to e, or null if no such
element.
Q6. List any five methods of Queue interface with their purpose.
• offer(E e): Inserts the element e into the queue if possible. Returns true on success, false if
the queue is full (capacity-constrained). Preferred over add() as it doesn't throw exception.
• poll(): Retrieves and removes the head. Returns null if queue is empty.
• peek(): Retrieves (but does not remove) the head. Returns null if empty.
• add(E e): Adds element to queue. Throws IllegalStateException if full.
• remove(): Retrieves and removes head. Throws NoSuchElementException if empty.
Q7. List any five methods of Deque interface with their purpose.
• addFirst(E e): Inserts e at the front of the deque. Throws IllegalStateException if full.
• addLast(E e): Inserts e at the end of the deque.
• pollFirst(): Retrieves and removes the first element; returns null if empty.
• pollLast(): Retrieves and removes the last element; returns null if empty.
• peekFirst(): Retrieves but does not remove the first element; returns null if empty.
Q8. With an example explain the usage of ArrayList.
ArrayList is a resizable array implementation of the List interface. It allows dynamic addition
and removal of elements, supports index-based access, and allows duplicates.
import [Link].*;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
[Link]("C");
[Link]("A");
[Link]("E");
[Link]("B");
[Link]("Size: " + [Link]()); // 4
[Link]([Link](0)); // C
[Link]("E");
for(String s : al)
[Link](s + " "); // C A B
}
}
Key points: ArrayList grows automatically; supports get(index) in O(1); remove() shifts
elements.
Page 21 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Q9. Write a Java program demonstrating conversion of ArrayList to array using
toArray().
import [Link].*;
public class ToArrayDemo {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
[Link]("Alpha"); [Link]("Beta"); [Link]("Gamma");
// Convert to Object[]
Object[] oa = [Link]();
[Link]("Object array:");
for(Object o : oa) [Link](o + " ");
// Convert to String[]
String[] sa = new String[[Link]()];
sa = [Link](sa);
[Link]("\nString array:");
for(String s : sa) [Link](s + " ");
}
}
Q10. Write a Java program demonstrating the usage of LinkedList.
import [Link].*;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<String> ll = new LinkedList<String>();
[Link]("F"); [Link]("B"); [Link]("D"); [Link]("E");
[Link]("A"); // A F B D E
[Link]("Z"); // A F B D E Z
[Link](ll);
[Link](); // remove A
[Link](); // remove Z
[Link](ll); // [F, B, D, E]
[Link]("First: " + [Link]());
[Link]("Last: " + [Link]());
}
}
Q11. Explain four constructors of the HashSet class.
• HashSet(): Creates an empty hash set with default initial capacity (16) and load factor
(0.75).
• HashSet(int capacity): Creates a hash set with specified initial capacity. Reduces rehashing
for known-size data.
• HashSet(int capacity, float fillRatio): Creates a hash set with both specified capacity and
load factor. fillRatio (0.0–1.0) controls when the set is rehashed.
• HashSet(Collection c): Creates a hash set containing all elements from the given collection.
Useful for converting a list or other collection to a set (removing duplicates).
Q12. What is an iterator? Explain with an example.
Page 22 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
An Iterator is an object that allows sequential traversal of a collection. The Iterator interface
([Link]) provides methods to iterate and optionally remove elements.
Methods: hasNext() — tests if more elements; next() — returns next element; remove() —
removes last element returned.
import [Link].*;
public class IteratorDemo {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<>();
[Link]("Alpha"); [Link]("Beta"); [Link]("Gamma");
Iterator<String> itr = [Link]();
while([Link]()) {
String s = [Link]();
[Link](s);
}
}
}
Q13. Explain the usage of the for-each loop with collections. Compare with Iterator.
The for-each loop (enhanced for) provides a simpler way to iterate over collections and arrays.
It implicitly uses an Iterator internally.
ArrayList<String> al = new ArrayList<>();
[Link]("A"); [Link]("B"); [Link]("C");
for(String s : al)
[Link](s);
Comparison:
• For-each: Simpler, more readable. Cannot remove elements during iteration. Cannot
access the index.
• Iterator: More control — can remove elements safely during traversal using [Link]().
Explicit, slightly more verbose.
• For-each is preferred for read-only traversal; Iterator is preferred when modification during
traversal is needed.
Q14. Explain how to store objects of user-defined classes in Java collections.
User-defined class objects can be stored in any collection. For sorted collections (TreeSet,
TreeMap), the class must either implement Comparable (natural ordering) or a Comparator
must be provided.
class Student implements Comparable<Student> {
String name; int age;
Student(String n, int a) { name=n; age=a; }
public int compareTo(Student s) { return [Link]([Link]); }
public String toString() { return name + "(" + age + ")"; }
}
TreeSet<Student> ts = new TreeSet<>();
[Link](new Student("Alice", 20));
[Link](new Student("Bob", 22));
for(Student s : ts) [Link](s);
Output: Alice(20), Bob(22) — sorted alphabetically by name.
Page 23 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Q15. Write how Vector differs from ArrayList.
• Synchronization: Vector is synchronized (thread-safe). All methods are synchronized.
ArrayList is not synchronized and not thread-safe by default.
• Performance: Because of synchronization overhead, Vector is slower than ArrayList in
single-threaded applications.
• Growth rate: Vector doubles its capacity when it grows (default). ArrayList increases by
50% of current size.
• Legacy: Vector is a legacy class from Java 1.0. ArrayList was introduced with the
Collections Framework in Java 2 and is preferred for new code.
Q16. Write the usage of any four methods of Map interface.
• put(K key, V value): Associates the specified value with the specified key. If the key already
exists, the value is replaced. Returns the old value or null.
• get(Object key): Returns the value mapped to the specified key, or null if the map contains
no mapping for the key.
• remove(Object key): Removes the mapping for the specified key and returns the associated
value, or null if not found.
• containsKey(Object key): Returns true if the map contains a mapping for the specified key.
Used to check before calling get() to avoid null values.
Q17. Write a Java program demonstrating the usage of HashMap.
import [Link].*;
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String, Integer> hm = new HashMap<>();
[Link]("John", 98);
[Link]("Mary", 87);
[Link]("Bob", 92);
[Link]([Link]("John")); // 98
[Link]([Link]("Mary")); // true
// Iterate using entrySet
Set<[Link]<String,Integer>> set = [Link]();
for([Link]<String,Integer> e : set)
[Link]([Link]() + " = " + [Link]());
}
}
Q18. Write a Java program demonstrating a custom Comparator for reverse order
sorting.
import [Link].*;
class ReverseComp implements Comparator<String> {
public int compare(String a, String b) {
return [Link](a); // reversed
}
}
public class CompDemo {
public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<>(new ReverseComp());
Page 24 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
[Link]("Charlie"); [Link]("Alpha"); [Link]("Beta");
for(String s : ts)
[Link](s); // Charlie, Beta, Alpha
}
}
Q19. Write the usage of any four collection algorithms.
• sort(List list): Sorts the elements of a List into ascending order. Uses natural ordering or a
Comparator. Example: [Link](al);
• binarySearch(List list, T key): Searches a sorted list for the specified key using binary
search. Returns index if found, negative if not. List must be sorted first.
• shuffle(List list): Randomly permutes the elements of the list. Useful for randomizing order
(e.g., shuffling a deck of cards).
• reverse(List list): Reverses the order of elements in the list. Example:
[Link](al);
Q20. Write a program to convert a given array into a collection with asList().
import [Link].*;
public class AsListDemo {
public static void main(String[] args) {
String[] arr = {"Alpha", "Beta", "Gamma", "Delta"};
// Convert array to List
List<String> list = [Link](arr);
[Link]("List: " + list);
// Use in a collection operation
[Link]("Contains Beta: " + [Link]("Beta"));
// Can also pass to ArrayList for modifiable list
ArrayList<String> al = new ArrayList<>(list);
[Link]("Epsilon");
[Link]("ArrayList: " + al);
}
}
Q21. Explain the roles and responsibilities of Model, View, and Controller in MVC.
Model:
• Represents the application's data and business logic.
• Manages database operations: read, create, update, delete.
• Is independent of the UI — no presentation logic.
• Notifies View when data changes (Observer pattern).
View:
• Presents the data from the Model to the user.
• Handles the UI display (HTML pages, JSP, Swing forms).
• Does not contain business logic; only presentation.
• Receives rendering instructions from the Controller.
Controller:
• Acts as the intermediary between Model and View.
• Receives user input (HTTP request, button click).
Page 25 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• Calls the appropriate Model method to process data.
• Selects the appropriate View to render the response.
Q22. Explain the flow of execution when a user interacts with an MVC-based Java
web application.
• Step 1 — User Request: The user performs an action (submits a form, clicks a link). The
browser sends an HTTP request to the server (Controller).
• Step 2 — Controller Receives Request: A Servlet (Controller) intercepts the request. It
parses the input parameters and determines what action to take.
• Step 3 — Model Interaction: The Controller invokes the appropriate Model (business logic
class or DAO) to process the data — e.g., query the database, validate input.
• Step 4 — Model Returns Data: The Model processes the request and returns the result
(e.g., a list of records) to the Controller. The Model does not know about the View.
• Step 5 — Controller Selects View: The Controller places the data in request/session scope
and forwards/redirects to a View (JSP page).
• Step 6 — View Renders Response: The JSP (View) reads the data from the request scope,
generates an HTML response, and sends it back to the user's browser.
Page 26 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
UNIT 3: String Handling and RMI
Section A: Short Answer Questions (2 Marks)
Q1. Write any two differences between StringBuffer and StringBuilder.
• Synchronization: StringBuffer is synchronized (thread-safe) — all its methods are
synchronized. StringBuilder is not synchronized and is not thread-safe.
• Performance: StringBuilder is faster than StringBuffer because it avoids the overhead of
synchronization. Use StringBuilder in single-threaded contexts; StringBuffer in multi-
threaded ones.
Q2. Write the purpose of the + operator in string handling with an example.
The + operator is overloaded in Java for String concatenation. It joins two strings into one new
string.
String s1 = "Hello";
String s2 = " World";
String s3 = s1 + s2; // "Hello World"
When one operand is a String and the other is a non-String, the non-String is automatically
converted via toString() before concatenation.
Q3. Write two ways to create a String object, with an example for each.
• Using string literal: String s = "Hello"; — The JVM checks the string pool; if the literal exists,
it reuses it.
• Using new keyword: String s = new String("Hello"); — Always creates a new object in heap
memory, even if an identical string exists in the pool.
Q4. What is the purpose of the toString() method in the context of strings?
The toString() method converts an object to its String representation. Every Java class inherits
it from Object. It is automatically called when an object is used in a string context (e.g.,
concatenation with +).
Wrapper classes override toString() to return the string form of their value. Custom classes
should override it for meaningful output.
Q5. How to initialize String objects using string literals?
String literals are enclosed in double quotes. The JVM maintains a string pool (intern pool) for
string literals:
String s1 = "Hello";
String s2 = "World";
String s3 = "Hello"; // reuses s1's object from pool
s1 == s3 is true because both point to the same object in the string pool, unlike objects created
with new.
Page 27 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Q6. What are the different ways to extract individual characters? Give the syntax.
• charAt(int index): Returns the character at the specified index. char ch = [Link](0);
• getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): Copies characters to a char
array.
• getBytes(): Returns a byte array of the string.
• toCharArray(): Converts the entire string to a char array. char[] ca = [Link]();
Q7. Provide syntax and an example for charAt().
char charAt(int where)
// where must be in range 0 to length()-1
String s = "Hello";
char c = [Link](1); // c = 'e'
If where is outside the valid range, charAt() throws a StringIndexOutOfBoundsException.
Q8. Write the purpose and syntax of regionMatches().
regionMatches() compares a specific region of a string with a specific region of another string.
It returns true if the regions match.
// Case-sensitive:
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int
numChars)
// Case-insensitive:
boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int
str2StartIndex, int numChars)
Q9. Demonstrate startsWith() and endsWith() methods.
• startsWith(String prefix): Returns true if the string begins with the specified prefix.
• endsWith(String suffix): Returns true if the string ends with the specified suffix.
String s = "HelloWorld";
[Link]([Link]("Hello")); // true
[Link]([Link]("World")); // true
[Link]([Link]("World")); // false
Q10. What's the difference between equals() and ==?
• equals(): Compares the content (character sequence) of two String objects. Returns true if
both strings have the same characters. Recommended for string value comparison.
• ==: Compares references (memory addresses). Returns true only if both variables point to
the exact same object. Two string objects with identical content but different references will
return false with ==.
Q11. Describe indexOf() and lastIndexOf() for string manipulation.
• indexOf(String str): Returns the index of the first occurrence of str in the string. Returns -1 if
not found. Searches from left to right.
Page 28 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• lastIndexOf(String str): Returns the index of the last occurrence of str in the string. Returns
-1 if not found. Searches from right to left.
Q12. What are the two forms of substring() and what do their arguments represent?
String substring(int startIndex)
Returns substring from startIndex to the end of the string.
String substring(int startIndex, int endIndex)
Returns substring from startIndex up to (but not including) endIndex.
Example: "Hello".substring(1) = "ello"; "Hello".substring(1,3) = "el"
Q13. Describe the two forms of replace() and their functionalities.
String replace(char original, char replacement)
Replaces all occurrences of a character with another character.
String replace(CharSequence original, CharSequence replacement)
Replaces all occurrences of a character sequence (substring) with another. Example:
"Hello".replace('l','r') = "Herro"
Q14. What is the purpose of valueOf() in Java and how does it relate to toString()?
[Link]() converts various data types (int, double, boolean, char, Object) to their String
representation. It is the reverse of parse methods.
For Object types, valueOf(obj) calls [Link](). So valueOf() is essentially a static gateway
to toString() for primitives and objects.
String s = [Link](42); // "42"
String s2 = [Link](3.14); // "3.14"
Q15. How does StringBuffer differ from String in terms of mutability and growth?
• Mutability: String objects are immutable — once created, their content cannot be changed.
Operations like replace or concat create new String objects. StringBuffer is mutable — its
content can be modified in place.
• Growth: A StringBuffer has an internal capacity that grows automatically when needed.
When the buffer is full, a new larger array is allocated. String has no concept of capacity as
it cannot grow.
Q16. What is the purpose of ensureCapacity() in StringBuffer?
ensureCapacity() pre-allocates capacity in a StringBuffer to avoid frequent reallocations when
large amounts of text will be appended.
General form: void ensureCapacity(int minCapacity)
If the current capacity is less than minCapacity, the capacity is increased. This is useful for
performance when you know the approximate final size in advance.
Q17. How does setLength() modify StringBuffer length?
setLength(int len) sets the length of the string within a StringBuffer.
Page 29 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• If len is less than the current length, the string is truncated — characters beyond len are
lost.
• If len is greater than the current length, null characters ('\0') are appended to pad to the new
length.
Q18. What do charAt() and setCharAt() do in StringBuffer?
• charAt(int where): Returns the character at the specified index (same as [Link]()).
Read-only access to a character.
• setCharAt(int where, char ch): Sets the character at the specified index to ch. Modifies the
StringBuffer in place, which is not possible with String.
Q19. What does the append() method do in StringBuffer?
append() concatenates the string representation of any value to the end of the invoking
StringBuffer object. It has multiple overloaded forms for different types.
For each parameter, toString() (or its equivalent) is called to obtain the string representation.
Example:
StringBuffer sb = new StringBuffer("Hello");
[Link](" ").append(42); // "Hello 42"
Q20. What does insert() do in StringBuffer and how is it different from append()?
insert() inserts a string (or primitive/object) at the specified position within the StringBuffer,
shifting existing characters to the right.
Difference: append() always adds to the end of the buffer. insert() adds at any specified index
position.
StringBuffer sb = new StringBuffer("Hello World");
[Link](5, " Beautiful");
// Result: "Hello Beautiful World"
Q21. How does StringBuilder differ from StringBuffer?
• Synchronization: StringBuffer is synchronized (thread-safe). StringBuilder is not
synchronized and should only be used in single-threaded contexts.
• Performance: StringBuilder is faster than StringBuffer since it has no synchronization
overhead. The API is identical — both have the same methods (append, insert, delete,
etc.).
Q22. What are the roles of the Stub and Skeleton objects in RMI?
• Stub (Client-side proxy): Resides on the client. When the client calls a remote method, the
stub intercepts the call, marshals (serializes) the parameters, and sends them to the server.
• Skeleton (Server-side proxy): Resides on the server. It receives the incoming call from the
stub, unmarshals the parameters, invokes the actual remote object method, and returns the
result to the stub.
Q23. What is RMI?
Page 30 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
RMI (Remote Method Invocation) is a Java API that allows a Java object running in one JVM to
invoke methods on an object running in another JVM, possibly on a different physical machine.
RMI provides location transparency — the calling code looks nearly identical whether the
object is local or remote, using Java's object model across distributed systems.
Q24. What is Syntactic transparency?
Syntactic transparency in distributed computing means that remote procedure/method calls use
the same syntax as local calls. The programmer does not need to write different code to call a
remote method versus a local method — RMI achieves this through stubs.
Q25. What is Semantic transparency?
Semantic transparency means that a remote procedure call behaves exactly like a local call
from the programmer's perspective — same semantics (behavior, error handling, return
values). The distributed nature is hidden from the application logic.
Q26. What are the requirements for a class to be serializable?
• The class must implement the [Link] interface (a marker interface with no
methods).
• All instance variables of the class must be serializable or marked with the transient keyword
(which excludes them from serialization). Static variables are not serialized.
Q27. State two advantages of distributed computing over centralized computing.
• Scalability: Resources (processors, storage) can be added across multiple machines to
handle increased load. Centralized systems are limited by a single machine's capacity.
• Fault Tolerance: If one node fails, other nodes continue working. The system can be
designed with redundancy so failures don't bring down the entire application.
Q28. State any four key characteristics of a distributed computing system.
• Resource Sharing: Multiple computers share hardware and software resources (files,
databases, printers) across the network.
• Concurrency: Multiple processes run simultaneously on different machines, working on
related tasks.
• Openness: Systems follow standard protocols and interfaces allowing components from
different vendors to interoperate.
• Transparency: The distribution of components is hidden — the system appears as a single
coherent system to users and applications.
Q29. List the elements used in the working of RPC.
• Client: The calling program that initiates the remote procedure call.
• Client Stub: A local proxy that marshals parameters and sends the request to the server.
• Network (Transport Layer): The communication medium that carries the serialized call and
return values.
Page 31 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• Server Stub (Skeleton): Receives the request, unmarshals parameters, and invokes the
actual procedure on the server.
• Server: The remote machine that executes the actual procedure and returns the result.
Q30. Why is the RMI Registry important in RMI applications?
The RMI Registry is a naming service that acts as a directory. Servers register remote objects
with the registry under a name. Clients look up remote objects by name from the registry to
obtain a reference (stub).
Without the registry, clients would have no standard way to locate remote objects. It runs as a
separate process (rmiregistry) on the server machine.
Q31. Write any two limitations of distributed computing.
• Complexity: Designing, building, and debugging distributed systems is significantly more
complex than centralized systems. Network failures, partial failures, and concurrency
issues must all be handled.
• Security: Distributed systems have larger attack surfaces. Data transmitted across
networks can be intercepted; unauthorized access to remote resources is a significant
concern.
Q32. When does RMI callback occur?
RMI callback occurs when the server needs to call back a method on the client. Instead of the
client always initiating calls, the server invokes methods on a remote object that the client has
previously registered/passed to the server.
This is useful for event notification — the server notifies interested clients (who have registered
their remote reference) when data changes or events occur.
Section B: Long Answer Questions (4–6 Marks)
Q1. With syntax and example explain split() and regionMatches().
split(): Splits the string into an array of substrings based on a regex delimiter.
String[] split(String regExp)
String[] split(String regExp, int max) // max limits number of pieces
String s = "one,two,three,four";
String[] parts = [Link](",");
for(String p : parts) [Link](p);
// Output: one two three four
regionMatches(): Compares a region of one string with a region of another.
boolean regionMatches(int startIndex, String str2, int str2Start, int
numChars)
String s1 = "Hello World";
String s2 = "World Peace";
boolean b = [Link](6, s2, 0, 5); // true
[Link](b); // true ("World" matches)
Page 32 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Q2. With syntax and example explain getChars() and replace().
getChars(): Copies characters from a String into a char array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
String s = "Hello World";
char[] buf = new char[5];
[Link](6, 11, buf, 0); // copies "World"
[Link](buf); // World
replace(): Replaces all occurrences of a character or sequence.
String replace(char original, char replacement)
String replace(CharSequence original, CharSequence replacement)
String s2 = "Hello".replace('l', 'r'); // "Herro"
String s3 = "Hello World".replace("World", "Java"); // "Hello Java"
Q3. With syntax and example explain insert() and deleteCharAt() of StringBuffer.
insert(): Inserts a value at the specified index in the StringBuffer.
StringBuffer insert(int index, String str)
// (overloaded for int, double, char, boolean, Object, etc.)
StringBuffer sb = new StringBuffer("Hello World");
[Link](5, " Beautiful");
[Link](sb); // Hello Beautiful World
deleteCharAt(): Removes the character at the specified index.
StringBuffer deleteCharAt(int loc)
StringBuffer sb2 = new StringBuffer("Hello");
[Link](1); // removes 'e'
[Link](sb2); // Hllo
Q4. With syntax and example explain substring() and lastIndexOf() of StringBuffer.
substring(): Extracts a portion of the StringBuffer as a String.
String substring(int startIndex)
String substring(int startIndex, int endIndex)
StringBuffer sb = new StringBuffer("Hello World");
[Link]([Link](6)); // World
[Link]([Link](0, 5)); // Hello
lastIndexOf(): Returns the index of the last occurrence of a substring.
int lastIndexOf(String str)
int lastIndexOf(String str, int startIndex)
StringBuffer sb2 = new StringBuffer("ababab");
[Link]([Link]("ab")); // 4
Q5. Explain how to concatenate strings with other data types.
Java's + operator can concatenate a String with any other type. When a non-String operand is
used with +, Java automatically calls the appropriate conversion:
• For primitive types: The primitive is converted to its string form (e.g., 42 becomes "42").
• For objects: The object's toString() method is called.
int age = 25;
double gpa = 3.8;
boolean pass = true;
Page 33 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
String msg = "Age: " + age + ", GPA: " + gpa + ", Pass: " + pass;
// Output: Age: 25, GPA: 3.8, Pass: true
Internally, the compiler uses [Link]() for this concatenation, which is why
[Link]() and toString() are called for non-String types.
Q6. Explain character extraction methods of String class with examples.
• charAt(int index): Returns the char at the given index. "Hello".charAt(0) → 'H'
• getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin): Copies characters from the
string into a char array. Useful when processing substrings as char arrays.
• getBytes(): Encodes the string into a byte array using the platform's default charset. Useful
for I/O operations.
• toCharArray(): Converts the entire string to a new char array. Useful for character-by-
character processing.
String s = "Hello";
char[] ca = [Link]();
for(char c : ca) [Link](c + " "); // H e l l o
Q7. Explain any four string comparison methods with examples.
• equals(Object obj): Content comparison, case-sensitive. "Hello".equals("Hello") → true;
"Hello".equals("hello") → false.
• equalsIgnoreCase(String str): Content comparison, case-insensitive.
"Hello".equalsIgnoreCase("hello") → true.
• compareTo(String str): Lexicographic comparison. Returns 0 if equal, negative if calling
string is less, positive if greater. Used for sorting.
• regionMatches(): Compares a substring region of two strings. Can be case-sensitive or
case-insensitive based on the ignoreCase flag.
Q8. Explain the difference between indexOf() and lastIndexOf() with examples.
Both search for a character or substring within a string, but differ in search direction:
• indexOf(String str): Searches from left to right and returns the index of the FIRST
occurrence. Returns -1 if not found.
• lastIndexOf(String str): Searches from right to left and returns the index of the LAST
occurrence. Returns -1 if not found.
String s = "abcabcabc";
[Link]([Link]("abc")); // 0 (first)
[Link]([Link]("abc")); // 6 (last)
[Link]([Link]("xyz")); // -1 (not found)
Both methods also have overloaded versions that accept a starting index for the search.
Q9. Describe two common approaches for modifying Strings in Java with examples.
Since String is immutable, modification creates new String objects. Two approaches:
1. String methods (return new strings):
String s = "Hello World";
String s2 = [Link]("World", "Java"); // new string
String s3 = [Link](0, 5); // "Hello"
String s4 = [Link](); // "HELLO WORLD"
Page 34 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
2. StringBuffer/StringBuilder (mutable, modify in place):
StringBuffer sb = new StringBuffer("Hello World");
[Link](6, 11, "Java"); // modifies in place → "Hello Java"
[Link](5, 10); // removes characters in range
Use String methods for simple transformations; use StringBuffer/StringBuilder when multiple
modifications are needed for performance.
Q10. Explain the use of charAt() and setCharAt() with examples.
charAt() — String and StringBuffer:
String s = "Hello";
char c = [Link](1); // c = 'e'
setCharAt() — StringBuffer only (String is immutable):
StringBuffer sb = new StringBuffer("Hello");
[Link](0, 'J'); // changes 'H' to 'J'
[Link](sb); // "Jello"
Key difference: charAt() only reads a character; setCharAt() modifies it in place, which is why it
is only available on the mutable StringBuffer and StringBuilder.
Q11. Explain the purpose of valueOf() in String class with an example.
[Link]() is a static method that converts any primitive type or object to its String
representation. It provides a clean way to convert data types to strings without concatenation.
int i = 42;
double d = 3.14;
boolean b = true;
char[] ca = {'H','i'};
[Link]([Link](i)); // "42"
[Link]([Link](d)); // "3.14"
[Link]([Link](b)); // "true"
[Link]([Link](ca)); // "Hi"
For objects, valueOf(obj) is equivalent to obj == null ? "null" : [Link]().
Q12. What is the use of replace() method? Explain.
The replace() method in String creates a new string with all occurrences of a character or
substring replaced. There are two forms:
// Form 1: Replace character
String replace(char original, char replacement)
String s1 = "Hello".replace('l','r'); // "Herro"
// Form 2: Replace CharSequence
String replace(CharSequence original, CharSequence replacement)
String s2 = "I like cats".replace("cats","dogs"); // "I like dogs"
replace() replaces ALL occurrences (unlike replaceFirst()). It returns a new String since String
is immutable. For StringBuffer, replace(int start, int end, String str) replaces a region.
Q13. With an example explain four methods of StringBuffer class.
• append(String s): Adds s to the end of the StringBuffer. "Hello".append(" World") → "Hello
World"
Page 35 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• insert(int index, String s): Inserts s at position index. "Hello World".insert(5, " Beautiful") →
"Hello Beautiful World"
• delete(int start, int end): Removes characters from start to end-1. "Hello World".delete(5,11)
→ "Hello"
• reverse(): Reverses the character sequence. "Hello".reverse() → "olleH"
StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // Hello World
[Link](5, "!"); // Hello! World
[Link](5, 7); // HelloWorld
[Link](); // dlroWolleH
Q14. What is the usage of delete() and deleteCharAt() methods?
delete(): Removes a range of characters from start index to end-1 index.
StringBuffer delete(int startIndex, int endIndex)
StringBuffer sb = new StringBuffer("Hello World");
[Link](5, 11); // removes " World" → "Hello"
deleteCharAt(): Removes exactly one character at the specified index.
StringBuffer deleteCharAt(int loc)
StringBuffer sb2 = new StringBuffer("Hello");
[Link](2); // removes 'l' → "Helo"
Both methods modify the StringBuffer in place and return the modified StringBuffer (allowing
method chaining).
Q15. Explain in detail the method used by the RMI client to connect to remote RMI
servers.
The RMI client uses the [Link]() method to obtain a reference to a remote object from
the RMI Registry.
Remote obj = [Link]("rmi://hostname:port/objectName");
Steps involved:
• Step 1: The client calls [Link]() with the URL of the remote object (host, port,
name).
• Step 2: The RMI runtime contacts the RMI Registry on the specified host and port.
• Step 3: The Registry returns the stub (proxy) for the remote object.
• Step 4: The client casts the returned stub to the remote interface type.
• Step 5: The client invokes methods on the stub, which marshals parameters and forwards
calls to the server.
MyRemote obj = (MyRemote) [Link]("rmi://localhost/MyServer");
String result = [Link](); // remote call
Q16. Explain object persistence and serialization in Java.
Object Persistence: The ability to save the state of an object (its data/fields) to a durable
storage medium (file, database) so that it can be retrieved and restored later, even after the
JVM terminates.
Serialization: The process of converting an object's state into a byte stream that can be saved
to a file, database, or transmitted over a network.
Deserialization: The reverse process — reconstructing an object from a byte stream.
Requirements for Serialization:
Page 36 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• The class must implement [Link] interface.
• Fields to be excluded are marked transient.
import [Link].*;
class Student implements Serializable {
int roll; String name;
}
// Serialize:
ObjectOutputStream out = new ObjectOutputStream(new
FileOutputStream("[Link]"));
[Link](new Student());
// Deserialize:
ObjectInputStream in = new ObjectInputStream(new
FileInputStream("[Link]"));
Student s = (Student) [Link]();
Q17. Explain four key challenges associated with distributed computing.
• Network Failures: Unlike local systems, distributed systems depend on networks. Network
failures can cause partial failures where some nodes are unreachable while others work
normally, making fault detection and recovery complex.
• Concurrency: Multiple nodes access and modify shared resources simultaneously,
requiring careful synchronization to prevent race conditions and data inconsistency.
• Heterogeneity: Nodes may run different hardware, operating systems, programming
languages, and network protocols. Ensuring interoperability across heterogeneous
environments is challenging.
• Security: Data transmitted over networks is vulnerable to interception, unauthorized access,
and attacks. Authentication, encryption, and access control must be carefully implemented.
Q18. Describe the three key components of a Distributed Computing System.
• Compute Nodes: Individual computers (servers, workstations, or virtual machines) that
perform computation. Each node has its own processor, memory, and storage, and runs its
own OS instance.
• Communication Network: The interconnection infrastructure (LAN, WAN, internet) that
enables nodes to exchange data and coordinate. The network's speed and reliability
directly affect system performance.
• Middleware: A software layer between the OS and applications that provides common
services (naming, security, coordination, messaging) to hide the complexity and
heterogeneity of the distributed infrastructure. Examples: RMI, CORBA, REST.
Q19. Explain how a Social Media platform is a Distributed Computing System.
A social media platform like Facebook/Twitter is a classic example of distributed computing:
• Data Storage Nodes: User data (profiles, posts, images) are stored across thousands of
servers distributed globally. No single server holds all data.
• Application Servers: Multiple web/application servers handle incoming user requests in
parallel, providing horizontal scalability.
• Content Delivery Network (CDN): Media content is cached and served from servers
geographically close to users, reducing latency.
• Message Queue Systems: Notifications, likes, and updates are propagated asynchronously
through distributed message queues to all relevant users.
Page 37 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• Load Balancers: Distribute incoming traffic across available servers to prevent overload on
any single node.
Q20. Explain the concept of Remote Procedure Calls (RPC) and its five key
elements.
RPC (Remote Procedure Call) is a protocol that allows a program to execute a procedure
(subroutine) on another computer in a network as if it were a local call. The calling program
need not explicitly code the communication details.
Five key elements:
• Client: The program that initiates the RPC request. It calls the remote procedure as if it
were a local function.
• Client Stub: A local proxy for the remote procedure. It marshals (serializes) the parameters
and sends the request to the server over the network.
• Transport Protocol: The networking layer (TCP/UDP) that carries the serialized request and
response between client and server.
• Server Stub (Skeleton): Receives the network request, unmarshals parameters, and calls
the actual procedure on the server.
• Server: Executes the procedure, and the result travels back through the same chain (stub
→ network → client stub → client).
Q21. What is RMI? Explain its key components.
RMI (Remote Method Invocation) is Java's mechanism for distributed object computing. It
allows objects in one JVM to invoke methods on objects in another JVM, possibly on a different
machine, using Java's object model.
Key Components:
• Remote Interface: An interface extending [Link] that declares the methods
accessible remotely. Each method must throw RemoteException.
• Remote Object (Server): A class implementing the remote interface and extending
UnicastRemoteObject. This is the actual object whose methods will be called remotely.
• Stub: A client-side proxy that represents the remote object. It marshals method calls and
parameters to the server.
• RMI Registry: A naming service (rmiregistry process) that binds remote object names to
their stubs. Clients look up objects by name.
• Client: Looks up the remote object via [Link](), gets a stub, and calls methods
through it.
Q22. Write short note on RMI Registry.
The RMI Registry is a simple naming service provided by Java RMI. It acts as a telephone
directory for remote objects:
• The server binds (registers) remote objects with the registry using [Link]("name",
remoteObject) or [Link]().
• The client looks up the object using [Link]("rmi://host/name"), which returns a
stub.
• The registry runs as a separate process started with the rmiregistry command, typically on
port 1099.
• [Link]() can be used to list all registered names.
• [Link]() removes a registration.
Page 38 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Without the registry, clients and servers must exchange object references through some other
mechanism, making the registry essential for standard RMI applications.
Q23. Outline the key steps involved in developing a basic RMI application.
• Step 1 — Define Remote Interface: Create an interface extending [Link] with
remote methods that throw RemoteException.
• Step 2 — Implement Remote Interface: Create a class extending UnicastRemoteObject
that implements the remote interface. Implement all remote methods.
• Step 3 — Write the Server: Instantiate the remote object, start the RMI Registry
([Link](1099)), and register the object using [Link]().
• Step 4 — Write the Client: Use [Link]() to get the remote object stub. Cast it to the
remote interface type and invoke remote methods.
• Step 5 — Compile and Run: Compile all classes. Start the RMI registry (rmiregistry). Run
the server, then run the client.
Q24. Explain the Advantages and Disadvantages of distributed computing.
Advantages:
• Scalability: Resources can be added across multiple machines to handle growing
workloads.
• Fault Tolerance: Redundant nodes ensure the system continues working even when some
nodes fail.
• Performance: Tasks can be executed in parallel across multiple nodes, reducing response
times.
• Resource Sharing: Hardware and software resources (databases, printers) can be shared
efficiently.
Disadvantages:
• Complexity: Design, implementation, and debugging of distributed systems is significantly
more complex.
• Security Risks: Network communication introduces vulnerabilities to eavesdropping, man-
in-the-middle attacks, etc.
• Network Dependency: Performance depends heavily on network reliability and bandwidth.
• Data Consistency: Maintaining consistent data across multiple nodes is challenging (CAP
theorem trade-offs).
Page 39 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
UNIT 4: Servlets, JSP and JDBC
Section A: Short Answer Questions (2 Marks)
Q1. What are servlets?
Servlets are Java programs that run on a web server and handle client requests (usually
HTTP) and generate responses (usually HTML). They extend the functionality of servers —
specifically to generate dynamic web content.
Servlets run inside a servlet container (like Apache Tomcat) and follow a request-response
lifecycle managed by the container.
Q2. List the drawbacks of CGI programs.
• Performance: CGI creates a new process for every request. Under heavy load, this creates
many processes, consuming large amounts of memory and CPU.
• Not persistent: CGI processes are killed after each request, so there is no way to cache
data between requests.
• Platform dependency: CGI scripts are often written in Perl or shell scripts, making them less
portable than Java servlets.
Q3. List the advantages of servlets.
• Performance: Servlets run within the web server's JVM — a thread is created per request
(not a process). Much faster than CGI.
• Portability: Written in Java, servlets are platform-independent and run on any server with a
servlet container.
• Persistence: Servlet objects remain in memory between requests, allowing caching of data
and database connections.
Q4. With syntax write the purpose of getParameter().
getParameter() retrieves the value of a specific form field or query string parameter sent by the
client in an HTTP request.
String getParameter(String paramName)
Returns the value of the named parameter as a String. Returns null if the parameter does not
exist. Example: String name = [Link]("username");
Q5. What is the purpose of extending GenericServlet class?
GenericServlet provides a convenient base class for writing protocol-independent servlets. It
implements the Servlet and ServletConfig interfaces and provides default implementations for
most methods.
Key methods provided: init(), destroy(), getServletConfig(), getServletInfo(), log(). Subclasses
need only override service() to handle requests.
Page 40 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Q6. Explain the role of ServletRequest and ServletResponse objects in service().
• ServletRequest: Encapsulates the client's request. Provides access to request parameters,
attributes, input stream, and client information via methods like getParameter(),
getAttribute(), getInputStream().
• ServletResponse: Encapsulates the server's response. Provides methods to send data
back to the client: getWriter() for text output, getOutputStream() for binary output,
setContentType() to set MIME type.
Q7. What is ServletConfig Interface? Mention any 2 methods.
ServletConfig is an interface that allows a servlet to obtain initialization parameters and its
servlet context during initialization.
• getInitParameter(String name): Returns the value of the specified initialization parameter
from the [Link] deployment descriptor.
• getServletContext(): Returns the ServletContext object, giving access to the web
application's context.
Q8. What is the purpose and significance of getWriter()?
getWriter() returns a PrintWriter object that the servlet uses to write character-based
(text/HTML) data back to the client.
PrintWriter getWriter() throws IOException
It must be called after setContentType() to ensure proper encoding. For binary data,
getOutputStream() is used instead. This is the primary way servlets send HTML responses.
Q9. Fill: ___ declares lifecycle methods for a servlet and ___ allows servlets to get
initialization parameters.
The Servlet interface declares lifecycle methods (init(), service(), destroy()) for a servlet, and
the ServletConfig interface allows servlets to get initialization parameters.
Q10. What is the role of getServletConfig() and getServletInfo() in the Servlet
interface?
• getServletConfig(): Returns the ServletConfig object passed to the servlet's init() method.
Used to retrieve initialization parameters and context.
• getServletInfo(): Returns a String that provides information about the servlet (author,
version, copyright). Override to provide meaningful information.
Q11. Differentiate getInitParameter() and getInitParameterNames() in ServletConfig.
• getInitParameter(String param): Returns the value of a specific named initialization
parameter as a String. Returns null if the parameter doesn't exist.
• getInitParameterNames(): Returns an Enumeration of String objects containing the names
of all initialization parameters. Used to iterate over all parameters.
Q12. Purpose and usage of getAttribute() and setAttribute() in ServletContext.
Page 41 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• getAttribute(String attr): Retrieves an object that has been previously stored in the context
under the given name. Returns null if no attribute exists with that name.
• setAttribute(String attr, Object val): Stores an object in the servlet context under the given
name, making it accessible to all servlets in the web application (application-wide scope).
Q13. What is the purpose of getParameterNames() and getParameterValues() in
ServletRequest?
• getParameterNames(): Returns an Enumeration of String objects containing the names of
all parameters in the request. Useful when you don't know the parameter names in
advance.
• getParameterValues(String name): Returns an array of String values for a parameter that
appears multiple times (e.g., checkboxes with same name). Returns null if not found.
Q14. What is the usage of readLine() in ServletInputStream?
readLine(byte[] buffer, int offset, int size) reads a line of bytes from the input stream into the
buffer starting at the specified offset. It reads until a newline character is found or size bytes
have been read.
Returns the number of bytes read, or -1 if end of input. Used for reading multipart form data or
raw request body content.
Q15. What's the specific purpose of ServletOutputStream and ServletInputStream?
• ServletOutputStream: Used to write binary data (images, PDF files) back to the client.
Obtained via [Link](). Also has a println() method for writing text.
• ServletInputStream: Used to read binary data (uploaded files, raw POST body) from the
client's request. Obtained via [Link]().
Q16. List classes provided in the [Link] package.
• HttpServlet: Abstract class that handles HTTP-specific requests. Provides doGet(),
doPost(), doPut(), doDelete() methods.
• HttpServletRequest: Extends ServletRequest with HTTP-specific methods for headers,
cookies, sessions.
• HttpServletResponse: Extends ServletResponse with HTTP-specific methods for status
codes and headers.
• HttpSession: Interface for managing user sessions. Cookie, HttpSessionEvent,
HttpSessionBindingEvent also belong to this package.
Q17. Write the usage of any two methods of HttpServletResponse interface.
• sendRedirect(String url): Sends a temporary redirect response to the client, directing them
to the specified URL. The browser makes a new request to the new URL.
• setContentType(String type): Sets the MIME type of the response (e.g., "text/html",
"image/jpeg"). Must be called before getWriter() or getOutputStream().
Q18. What is Cookie? How is it helpful?
Page 42 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
A Cookie is a small piece of data sent from the server to the client's browser and stored on the
client's machine. On subsequent requests, the browser sends the cookie back to the server.
Cookies are helpful for: session tracking (maintaining user login state), storing user
preferences, personalizing content, and tracking user behavior across multiple requests.
Q19. Describe the significance of valueBound and valueUnbound in
HttpSessionBindingListener.
• valueBound(HttpSessionBindingEvent e): Called when the object implementing
HttpSessionBindingListener is bound to a session (added as an attribute). Can be used to
initialize resources.
• valueUnbound(HttpSessionBindingEvent e): Called when the object is unbound from a
session (removed or session expires). Can be used to release resources like database
connections.
Q20. What information can be stored in a cookie?
• Name-value pairs: The core content — any string data like user ID, preferences, theme
choice, language setting.
• Metadata: Expiration time (setMaxAge()), domain (setDomain()), path (setPath()), and
security flag (setSecure()) control how and when the cookie is sent.
Q21. What is the significance of getSession() in HttpServletRequest?
getSession() returns the HttpSession object associated with the current request. If no session
exists, it creates a new one (when called with no argument or true).
HttpSession getSession() // create if not exists
HttpSession getSession(boolean create) // false = return null if not
exists
It is the primary way to access or create a session for maintaining user state across multiple
HTTP requests.
Q22. Write the purpose of next() and getString() in JDBC.
• next() (ResultSet): Advances the cursor to the next row in the ResultSet. Returns true if
there is a next row, false when all rows have been processed. Must be called before
reading the first row.
• getString(String columnName) or getString(int colIndex): Retrieves the value of a column
from the current row of a ResultSet as a String. Used to read text data from query results.
Q23. List the parts of the URL used in getConnection() to establish connection.
The JDBC URL format: jdbc:subprotocol:subname
• jdbc: — the protocol prefix (always 'jdbc').
• subprotocol: — the database driver identifier (e.g., odbc, mysql, oracle).
• subname: — the database identifier/address (e.g., database name,
hostname:port/database).
Example: jdbc:mysql://localhost:3306/mydb or jdbc:odbc:myDataSource
Page 43 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Q24. Write the purpose of setLoginTimeout() and getLoginTimeout().
• setLoginTimeout(int seconds): Sets the maximum time (in seconds) that a driver will wait
when attempting to connect to a database. Throws an exception if the connection is not
established within this time.
• getLoginTimeout(): Returns the current maximum login timeout in seconds. A value of 0
means the driver will wait indefinitely.
Q25. Write the purpose of forName() and createStatement().
• [Link](String className): Dynamically loads and registers the JDBC driver class.
Example: [Link]("[Link]") loads the MySQL driver.
• createStatement(): Creates a Statement object for sending SQL queries to the database.
Returns a Statement that can be used with executeQuery() or executeUpdate().
Q26. What is the main purpose of the JDBC to ODBC (Type 1) driver?
The Type 1 (JDBC-ODBC Bridge) driver translates JDBC calls to ODBC calls, allowing Java
applications to connect to any database that has an ODBC driver.
It is used primarily for prototyping or when no native JDBC driver is available. It is not suitable
for production because it requires ODBC to be installed on the client machine and has
performance overhead.
Q27. Differentiate between Type 3 and Type 4 JDBC drivers.
• Type 3 (Network Protocol Driver): Translates JDBC calls to a middleware-specific protocol,
which is then translated to the database protocol by a middleware server. Flexible but adds
network complexity.
• Type 4 (Thin Driver / Native Protocol): A pure Java driver that directly converts JDBC calls
to the database's native network protocol. No middleware needed. It is the fastest and most
commonly used driver for production applications.
Q28. Difference between executeQuery() and executeUpdate().
• executeQuery(String sql): Executes a SELECT SQL statement that returns a ResultSet.
Returns a ResultSet object containing the query results.
• executeUpdate(String sql): Executes INSERT, UPDATE, DELETE, or DDL SQL
statements. Returns an int representing the number of rows affected.
Q29. What does a ResultSet object represent in JDBC?
A ResultSet object represents the results of a SQL SELECT query — a table of data returned
from the database. It maintains a cursor pointing to its current row.
Initially the cursor is before the first row. The next() method moves the cursor forward row by
row. Data is retrieved using getXxx() methods (getString(), getInt(), etc.) by column name or
index.
Q30. Main advantage of PreparedStatement over Statement.
Page 44 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• Performance: PreparedStatement is precompiled by the database. For repeated
executions, it is significantly faster because the SQL is compiled only once.
• Security (SQL Injection prevention): PreparedStatement uses parameterized queries (?
placeholders). Values are set via setXxx() methods, which automatically escape special
characters, preventing SQL injection attacks.
Q31. How do PreparedStatement objects handle dynamic values?
PreparedStatement uses placeholders (?) in the SQL query for dynamic values. Before
execution, values are set for each placeholder using type-specific setter methods:
PreparedStatement ps = [Link]("SELECT * FROM emp WHERE id=?
AND name=?");
[Link](1, 101); // sets first ?
[Link](2, "Alice"); // sets second ?
ResultSet rs = [Link]();
Q32. What are the different parameters used by CallableStatement?
• IN parameters: Input values passed to the stored procedure. Set using setXxx() methods
(e.g., setInt(), setString()).
• OUT parameters: Values returned from the stored procedure. Must be registered using
registerOutParameter(index, sqlType) before calling execute().
• INOUT parameters: Used both as input and output. Set with setXxx() and read after
execution with getXxx().
Q33. How to Insert a Row into the ResultSet?
To insert a row into an updatable ResultSet:
• Step 1: Call moveToInsertRow() to move the cursor to the special insert row buffer.
• Step 2: Use updateXxx() methods (updateString(), updateInt(), etc.) to set column values.
• Step 3: Call insertRow() to insert the new row into both the ResultSet and the database.
[Link]();
[Link]("id", 5);
[Link]("name", "Bob");
[Link]();
Q34. Why are Savepoints used in database transactions?
Savepoints allow partial rollback within a transaction. Instead of rolling back the entire
transaction on an error, you can roll back to a specific savepoint, preserving work done before
that point.
Savepoint sp = [Link]("mySP");
// ... more SQL operations ...
[Link](sp); // only rolls back to mySP
Q35. How to batch SQL statements into transaction statements?
JDBC batch processing groups multiple SQL statements and sends them to the database in
one call, improving performance:
[Link](false);
Page 45 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
[Link]("INSERT INTO emp VALUES(1, 'Alice')");
[Link]("INSERT INTO emp VALUES(2, 'Bob')");
[Link]("UPDATE emp SET salary=50000 WHERE id=1");
int[] results = [Link]();
[Link]();
Q36. What are the methods supported by RowSetListener?
• rowSetChanged(RowSetEvent e): Called when the entire contents of the RowSet have
changed.
• rowChanged(RowSetEvent e): Called when a single row of the RowSet has been modified
(insert, update, or delete).
• cursorMoved(RowSetEvent e): Called when the cursor has moved to a different row.
Q37. What is JavaServerPages (JSP)?
JSP (JavaServer Pages) is a server-side technology that enables the creation of dynamic web
content by embedding Java code directly into HTML pages using special JSP tags.
JSP pages are automatically compiled to servlets by the JSP container the first time they are
accessed. They simplify web development by separating presentation (HTML) from business
logic (Java).
Q38. List any four advantages of using JSP.
• Separation of Presentation and Logic: HTML designers can work on JSP pages while Java
developers handle business logic in separate Java classes.
• Reusability: JavaBeans and custom tags can be shared across multiple JSP pages.
• Implicit Objects: JSP provides pre-defined objects (request, response, session, out) that are
immediately available without declaration.
• Platform Independence: Since JSP compiles to a Java servlet, it runs on any platform with
a servlet container.
Q39. List any four implicit objects in JSP.
• request: The HttpServletRequest object — access to client request parameters, headers,
and attributes.
• response: The HttpServletResponse object — send response headers and cookies.
• session: The HttpSession object — maintain user-specific data across requests.
• out: The JspWriter object — used to write output to the client (HTML content).
Q40. What is the usage of buffer attribute in JSP?
The buffer attribute in the JSP page directive specifies the buffering model for the output
stream to the client.
Syntax: <%@ page buffer="8kb" %> or <%@ page buffer="none" %>
With buffering, output is collected in memory before being sent to the client, allowing headers
(including cookies) to be set after some output has been written. The default buffer size is
typically 8kb.
Page 46 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
Q41. What is page Directive in JSP?
The page directive defines page-level attributes that apply to the entire JSP page. It is placed
at the top of the JSP file.
Syntax: <%@ page attribute="value" %>
Common attributes: language (scripting language, always "java"), contentType (MIME type),
import (Java classes to import), session (true/false), buffer (buffer size), errorPage (URL of
error handling page).
Section B: Long Answer Questions (4–6 Marks)
Q1. Explain the three key methods in the lifecycle of a servlet (init(), service(),
destroy()).
• init(ServletConfig config): Called once by the servlet container when the servlet is first
loaded. Used to perform initialization (establish DB connections, load configuration). The
ServletConfig parameter provides access to initialization parameters. Only called once
throughout the servlet's life.
• service(ServletRequest req, ServletResponse res): Called for every client request. The
container creates request and response objects and passes them to this method. For
HttpServlet, this dispatches to doGet(), doPost(), etc. based on the HTTP method. This is
the heart of the servlet — all request processing happens here.
• destroy(): Called once by the container when the servlet is being taken out of service
(server shutdown or redeployment). Used to release resources (close DB connections,
save state). After destroy() returns, the container waits for all threads to complete before
garbage collecting the servlet.
Q2. Develop a basic servlet program that displays a welcome message.
import [Link].*;
import [Link].*;
import [Link].*;
public class WelcomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><body>");
[Link]("<h1>Welcome to Servlet Programming!</h1>");
[Link]("<p>Your request has been processed.</p>");
[Link]("</body></html>");
}
}
This servlet extends HttpServlet, overrides doGet(), sets response content type to HTML,
obtains a PrintWriter, and writes an HTML response.
Q3. Explain the functionalities of methods available in ServletConfig Interface.
Page 47 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• getInitParameter(String name): Returns the value of the specified initialization parameter
defined in [Link] as a String. Returns null if the parameter doesn't exist. Example: String
dbURL = [Link]("dbURL");
• getInitParameterNames(): Returns an Enumeration of all initialization parameter names for
this servlet. Used to list all available init params.
• getServletContext(): Returns the ServletContext object for the web application. Used to
access application-wide attributes, log messages, and get real paths.
• getServletName(): Returns the name of the servlet as declared in [Link] (the <servlet-
name> value).
Q4. Write the usage of any four methods of ServletRequest interface.
• getParameter(String name): Returns the value of a named request parameter (form field or
query string). Returns null if not found.
• getParameterNames(): Returns an Enumeration of all parameter names in the request.
Useful for processing forms with many fields.
• getAttribute(String name): Returns the value of the named attribute that has been set by the
server or a filter. Attributes can be set using setAttribute().
• getInputStream(): Returns a ServletInputStream for reading the raw body of the request
(used for file uploads and binary data).
Q5. Write the usage of any four methods of ServletResponse interface.
• setContentType(String type): Sets the MIME type of the response (e.g.,
"text/html;charset=UTF-8"). Must be called before getWriter() or getOutputStream().
• getWriter(): Returns a PrintWriter for writing character-based (text/HTML) response output
to the client.
• getOutputStream(): Returns a ServletOutputStream for writing binary data (images, files) to
the client. Cannot be used after getWriter() is called.
• setBufferSize(int size): Sets the preferred buffer size for the response body. Larger buffers
allow more flexibility in setting headers before content is committed.
Q6. Write a Java servlet that handles HTTP POST requests containing form data.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class FormProcessorServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String name = [Link]("name");
String email = [Link]("email");
[Link]("<html><body>");
[Link]("<h2>Form Data Received</h2>");
[Link]("<p>Name: " + name + "</p>");
[Link]("<p>Email: " + email + "</p>");
Enumeration<String> params = [Link]();
[Link]("<h3>All Parameters:</h3>");
Page 48 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
while([Link]()) {
String param = [Link]();
[Link]("<p>" + param + ": " + [Link](param)
+ "</p>");
}
[Link]("</body></html>");
}
}
Q7. Explain the following methods of HttpServletRequest interface: getCookies,
getMethod, getPathInfo, getSession.
• getCookies(): Returns an array of Cookie objects sent by the client. Returns null if no
cookies are present. Used to read previously stored cookies.
• getMethod(): Returns the HTTP method of the request as a String ("GET", "POST", "PUT",
etc.). Useful for determining how the form was submitted.
• getPathInfo(): Returns any extra path information in the URL after the servlet path and
before the query string. Returns null if none. Example: for URL /servlet/extra/info, returns
/extra/info.
• getSession(): Returns the HttpSession associated with the current request. Creates a new
session if none exists. Used for session-based state management.
Q8. With an example, Explain the purpose and behavior of doGet() method.
doGet() handles HTTP GET requests. It is invoked when a user types a URL in a browser,
clicks a link, or submits a form with method="GET". GET parameters are appended to the URL
as a query string.
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String user = [Link]("username");
[Link]("<html><body>");
[Link]("<h2>Hello, " + user + "!</h2>");
[Link]("</body></html>");
}
Calling URL: [Link] — The servlet reads the 'username'
parameter and responds with a personalized greeting.
Q9. With an example, Explain the purpose and behavior of doPost() method.
doPost() handles HTTP POST requests. POST is used when sending sensitive data
(passwords) or large amounts of data. Parameters are sent in the request body, not visible in
the URL.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String user = [Link]("username");
String pass = [Link]("password");
Page 49 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
[Link]("<html><body>");
if("admin".equals(user) && "1234".equals(pass))
[Link]("<h2>Login Successful!</h2>");
else
[Link]("<h2>Invalid credentials.</h2>");
[Link]("</body></html>");
}
Q10. What are the different methods involved in session management in servlets?
• getSession(): Obtains the current session. HttpSession session = [Link]();
• setAttribute(String name, Object val): Stores an object in the session.
[Link]("user", "Alice");
• getAttribute(String name): Retrieves a stored object from the session. String user = (String)
[Link]("user");
• invalidate(): Destroys the session and removes all attributes. Called on logout.
• getId(): Returns the unique session ID string.
• setMaxInactiveInterval(int seconds): Sets the timeout after which the session is invalidated
if inactive.
Q11. How cookies can be handled using servlet.
Creating and sending a Cookie:
// Create:
Cookie c = new Cookie("username", "Alice");
[Link](60*60*24); // 1 day
[Link](c); // send to client
Reading cookies from client:
Cookie[] cookies = [Link]();
if(cookies != null) {
for(Cookie ck : cookies) {
if([Link]().equals("username"))
[Link]([Link]());
}
}
Deleting a cookie:
Cookie c = new Cookie("username", "");
[Link](0); // expire immediately
[Link](c);
Q12. Explain why JSP is a compelling choice for web development compared to
CGI.
• Performance: JSP is compiled to a servlet once and cached. Subsequent requests reuse
the compiled class. CGI creates a new process per request.
• Java Integration: JSP directly integrates with Java, allowing use of the entire Java
ecosystem (JDBC, JavaBeans, EJB, etc.) without translation layers.
• Implicit Objects: JSP provides pre-built objects (request, response, session, application)
without explicit declaration, reducing boilerplate code.
• Maintainability: JSP separates HTML presentation from Java logic. Designers can modify
HTML without touching Java code, unlike CGI where both are intermingled.
Page 50 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• Session Management: JSP has built-in, easy-to-use session tracking via the implicit
session object. CGI requires manual cookie/URL manipulation.
Q13. Explain the key steps in how a web server processes a JSP request.
• Step 1 — Client Request: The browser sends an HTTP request for a .jsp file.
• Step 2 — Translation: If the JSP has not been compiled (or has changed), the JSP
container translates the JSP page into a Java Servlet source file (.java).
• Step 3 — Compilation: The generated Java source is compiled into a bytecode (.class) file.
• Step 4 — Loading: The compiled servlet class is loaded into the JVM.
• Step 5 — Request Handling: The servlet's service() method is called. It generates the
HTML response (mixing static HTML with dynamic Java output).
• Step 6 — Response: The generated HTML is sent back to the browser. For subsequent
requests to the same JSP, the compiled class is reused (unless the JSP is modified).
Q14. Explain the key stages in the lifecycle of a JSP page.
• Translation Phase: The JSP file is translated into a Java Servlet source (.java) file by the
JSP engine. HTML becomes [Link]() calls; scriplets become inline Java code.
• Compilation Phase: The generated .java file is compiled into a .class file. This happens
once unless the JSP is modified.
• Initialization (jspInit()): Called once when the servlet is first loaded, similar to [Link]().
Used for one-time setup.
• Request Processing (_jspService()): Called for every client request. This method processes
the request and generates the response.
• Destruction (jspDestroy()): Called when the JSP is taken out of service. Used for cleanup,
similar to [Link]().
Q15. Write short note on JSP directives and JSP Actions.
JSP Directives:
Directives give special instructions to the JSP container. They do not produce output but affect
translation.
• <%@ page ... %>: Defines page-level attributes (contentType, import, session, buffer, etc.).
• <%@ include file="...": Includes another file's content at translation time (static include).
• <%@ taglib uri="..." prefix="...": Declares a tag library for use in the page.
JSP Actions:
Standard actions use XML-like tags to perform operations at request time.
• <jsp:include page="...">: Includes a page at request time (dynamic include — parameters
can be passed).
• <jsp:forward page="...">: Forwards the request to another resource (page, servlet).
• <jsp:useBean id="..." class="...">: Creates or locates a JavaBean.
• <jsp:setProperty ...>: Sets a property of a JavaBean.
Q16. Explain the steps in the JDBC process.
• Step 1 — Load the Driver: Use [Link]("driverClassName") to load and register the
JDBC driver. Example: [Link]("[Link]");
Page 51 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• Step 2 — Establish Connection: Use [Link](url, user, password) to
obtain a Connection object. Example: Connection con =
[Link]("jdbc:mysql://localhost/mydb", "root", "");
• Step 3 — Create Statement: Use [Link]() to get a Statement object for
executing SQL. Or [Link](sql) for a PreparedStatement.
• Step 4 — Execute Query: Call executeQuery(sql) for SELECT (returns ResultSet) or
executeUpdate(sql) for INSERT/UPDATE/DELETE (returns int).
• Step 5 — Process ResultSet: Iterate through the ResultSet using while([Link]()) and
retrieve data with getXxx() methods.
• Step 6 — Close Connection: Call [Link](), [Link](), [Link]() to release database
resources.
Q17. Write the steps to associate database with JDBC/ODBC bridge.
• Step 1 — Create ODBC Data Source: In Windows Control Panel → Administrative Tools →
ODBC Data Sources, create a System DSN pointing to your database file (e.g., Access,
dBASE).
• Step 2 — Load the JDBC-ODBC Bridge Driver:
[Link]("[Link]");
• Step 3 — Establish Connection: Connection con =
[Link]("jdbc:odbc:myDSN", "", ""); where myDSN is the ODBC data
source name.
• Step 4 — Create Statement and Execute: Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM tableName");
• Step 5 — Process and Close: Process the ResultSet and close all resources.
Q18. What is JDBC Driver? Explain different types.
A JDBC Driver is a software component that enables Java applications to communicate with a
database. It implements the [Link] interface.
• Type 1 — JDBC-ODBC Bridge: Translates JDBC calls to ODBC. Requires ODBC driver on
client. Only suitable for development/testing, not production.
• Type 2 — Native API Driver: Uses database vendor's native client libraries (C/C++).
Converts JDBC calls to native API calls. Faster than Type 1 but requires native libraries on
client.
• Type 3 — Network Protocol Driver: Sends JDBC calls to a middleware server using
database-independent protocol. Server translates to database-specific protocol. Flexible —
no client-side libraries needed.
• Type 4 — Native Protocol (Thin) Driver: Pure Java. Directly converts JDBC calls to the
database's native wire protocol. No middleware or native libraries. Fastest and most
portable. Preferred for production.
Q19. What are the JDBC statements? Explain.
• Statement: Basic interface for executing static SQL queries. Created via
[Link](). No parameterization. Use for DDL and simple DML. Example:
[Link]("SELECT * FROM emp");
• PreparedStatement: Precompiled SQL statement with IN parameters (? placeholders).
More efficient for repeated execution. Prevents SQL injection. Example:
PreparedStatement ps = [Link]("INSERT INTO emp VALUES(?,?)");
[Link](1,1); [Link](2,"Alice"); [Link]();
Page 52 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
• CallableStatement: Used to call stored procedures in the database. Supports IN, OUT, and
INOUT parameters. Example: CallableStatement cs = [Link]("{call
myProc(?,?)}"); [Link](1, id); [Link](2, [Link]);
[Link](); String result = [Link](2);
Q20. Describe Scrollable ResultSet and Updatable ResultSet.
Scrollable ResultSet:
By default, a ResultSet is forward-only (can only call next()). A scrollable ResultSet allows
movement in any direction using:
• next()/previous(): Move forward/backward one row.
• first()/last(): Move to first/last row.
• absolute(n): Move to row number n.
• relative(n): Move n rows from current position.
Created with: Statement stmt =
[Link](ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Updatable ResultSet:
Allows modifying data in the database directly through the ResultSet without writing separate
UPDATE/INSERT SQL.
• updateXxx() methods modify the current row's columns.
• updateRow() commits the changes to the database.
• deleteRow() deletes the current row.
• moveToInsertRow() / insertRow() adds a new row.
Created with: Statement stmt = [Link](ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
Q21. Write a note on DatabaseMetaData interface.
The DatabaseMetaData interface provides comprehensive information about the database as a
whole. It is obtained via: DatabaseMetaData dbmd = [Link]();
Key methods:
• getDatabaseProductName(): Returns the database product name (e.g., "MySQL").
• getDatabaseProductVersion(): Returns the database version string.
• getDriverName(): Returns the JDBC driver name.
• getTables(catalog, schema, tablePattern, types[]): Returns a ResultSet of tables in the
database matching the criteria.
• getColumns(catalog, schema, table, colPattern): Returns a ResultSet of column information
for a table.
DatabaseMetaData is useful for writing generic applications that work with multiple databases
and for inspecting schema at runtime.
Q22. Explain the types of Exceptions that occur in JDBC.
• SQLException: The primary exception class in JDBC. Thrown when a database access
error or other error occurs. Provides: getMessage() (description), getSQLState() (SQL state
code), getErrorCode() (vendor-specific error code), getNextException() (chains multiple
exceptions).
• SQLWarning: A subclass of SQLException that provides information about database
access warnings. Attached to connections, statements, and result sets. Retrieved via
Page 53 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat
VI Sem BCA — Advanced Java & J2EE | Question Bank with Answers
getWarnings() methods. Does not cause exceptions — warnings allow execution to
continue.
• BatchUpdateException: Thrown when an error occurs during batch update execution
(executeBatch()). Provides getUpdateCounts() to determine which statements in the batch
succeeded.
• DataTruncation: A SQLWarning subclass. Thrown when JDBC unexpectedly truncates a
data value. Provides getIndex() (column/parameter index) and getTransferSize() (bytes
transferred).
Page 54 | Mangalore University — NEP 2020 Compiled by Vadiraja Bhat