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

Ad Java QB Solved 2Marks

The document is a question bank for an Advanced Java and J2EE course, covering topics such as enumerations, type wrappers, annotations, Java Beans, and the Collections Framework. It includes definitions, method functionalities, examples, and differences between various concepts in Java. The content is structured into units with questions designed to test knowledge on key Java programming principles.

Uploaded by

navyashreeudupa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Ad Java QB Solved 2Marks

The document is a question bank for an Advanced Java and J2EE course, covering topics such as enumerations, type wrappers, annotations, Java Beans, and the Collections Framework. It includes definitions, method functionalities, examples, and differences between various concepts in Java. The content is structured into units with questions designed to test knowledge on key Java programming principles.

Uploaded by

navyashreeudupa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

VI SEMESTER BCA Advanced Java and J2EE Question Bank 1

Unit-1 (2 marks)
1. With the syntax write the purpose of ordinal() method.
Odrinal() method is used to obtain a value that indicates an enumeration constant’s
position in the list of constants. This is called its ordinal value, and it is retrieved by
calling the ordinal( ) method, shown here:
final int ordinal( )
It returns the ordinal value of the invoking constant. Ordinal values begin at zero.
2. List two key characteristics of enumeration constants in Java.
Two key characteristics of enumeration constants in Java are:
1. Enum constants are implicitly static and final.
This means that you cannot change the value of an enum constant once it is
created. You also cannot create a new instance of an enum constant.
2. Enum constants are strongly typed.
This means that you can only assign an enum constant to a variable of the same
enum type. For example, you cannot assign an enum constant of type Color to a
variable of type Integer.

3. What is an enumeration? How enumeration can be created?


An enumeration is a list of named constants. In Java, an enumeration defines a class
type. By making enumerations into classes, the capabilities of the enumeration are
greatly expanded.

An enumeration is created using the enum keyword.

4. Differentiate values() and valueOf() methods in Java enumerations.


The values( ) method returns an array that contains a list of the enumeration
constants. The valueOf( ) method returns the enumeration constant whose value
corresponds to the string passed in str. In both cases, enum-type is the type of the
enumeration.
Syntax:
public static enum-type [ ] values( )
public static enum-type valueOf(String str )

5. Provide an example of how to use the values() method to iterate through all
the constants in an enumeration.
Example for values() method to to iterate through all the constants in an enumeration.
enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
VI SEMESTER BCA Advanced Java and J2EE Question Bank 2

class EnumDemo2 {
public static void main(String args[])
{
Apple ap;
System.out.println("Here are all Apple constants:");
// use values()
Apple allapples[] = Apple.values();
for(Apple a : allapples) //Iteration
System.out.println(a);
} }
It prints all the Apple enum constants.

6. Give the functionalities of compareTo(), and equals() methods in Java


enumerations.
To compare the ordinal value of two constants of the same enumeration we use the
compareTo( ) method. It has this general form:
final int compareTo(enum-type e)
 Here, enum-type is the type of the enumeration, and e is the constant being
compared to the invoking constant. Remember, both the invoking constant and e
must be of the same enumeration.
We can compare for equality an enumeration constant with any other object by using
equals( ), which overrides the equals( ) method defined by Object.
public boolean equals(Object obj)
 Although equals( ) can compare an enumeration constant to any other object,
those two objects will be equal only if they both refer to the same constant, within
the same enumeration.

7. Why are type wrappers used in Java?


Java provides type wrappers, which are classes that encapsulate a primitive type
within an object. The type wrappers are Double, Float, Long, Integer, Short, Byte,
Character, and Boolean. These classes offer a wide array of methods that allow you to
fully integrate the primitive types into Java’s object hierarchy.

8. What is the purpose of the doubleValue() method in a numeric wrapper


class?(similarly other methods)
doubleValue( ) returns the value of an object as a double, floatValue( ) returns the value
as a float, and so on. These methods are implemented by each of the numeric type
wrappers.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 3

Ex: class Wrap {


public static void main(String args[]) {
Integer iOb = new Integer(100);
int i = iOb.intValue(); // here instead of int double can be used
System.out.println(i + " " + iOb); // displays 100 100
}

9. What is the benefit of autoboxing and auto-unboxing in Java?


Autoboxing is the process by which a primitive type is automatically encapsulated
(boxed) into its equivalent type wrapper whenever an object of that type is needed.
There is no need to explicitly construct an object.
Auto-unboxing is the process by which the value of a boxed object is automatically
extracted (unboxed) from a type wrapper when its value is needed. There is no need to
call a method such as intValue( ) or doubleValue( ).

10. What is retention policy? How to set retention policy? Give an example.
A retention policy determines at what point an annotation is discarded.
We can set retention policy by
@Retention.
Its general form is shown here:
@Retention(retention-policy)

Example:
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
11. List any two retention policies with its purpose.
Two retention policies with its purpose:
 An annotation with a retention policy of SOURCE is retained only in the source
file and is discarded during compilation.
 An annotation with a retention policy of CLASS is stored in the .class file during
compilation. However, it is not available through the JVM during run time.

12. What is the purpose of setting default values to annotation member. Write
the general form for setting default values.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 4

We can give annotation members default values that will be used if no value is
specified when the annotation is applied. A default value is specified by adding a
default clause to a member’s declaration.
General form:
type member( ) default value;

13. Define
a. Marker Annotation
b. Single Member Annotation.
A marker annotation is a special kind of annotation that contains no members.
Its sole purpose is to mark a declaration.

A single-member annotation contains only one member. It works like a normal


annotation except that it allows a shorthand form of specifying the value of the
member.

14. List any two built in annotations with its purpose.


Two built in annotations with its purpose
@Retention is designed to be used only as an annotation to another annotation. It
specifies the retention policy as described earlier in this chapter.
@Documented
The @Documented annotation is a marker interface that tells a tool that an
annotation is to be documented. It is designed to be used only as an annotation to an
annotation declaration.

15. Write any two restrictions on annotation.


Two restrictions on annotation:
1. Annotation types and their methods may not have type parameters
2. Annotation types and members cannot be made generic. The only valid use of
generics in annotation types is for methods whose return type is Class.
16. What is the primary purpose of annotations in Java code?
The primary purpose of annotations in Java code is to enable us to embed
supplemental information into a source file. It does not change the actions of a
program.

17. How are annotations declared in Java?Give example.


An annotation is created through a mechanism based on the interface. Declaration for an
annotation called MyAnno:
// A simple annotation type.
@interface MyAnno {
String str();
VI SEMESTER BCA Advanced Java and J2EE Question Bank 5

int val();
}
The @ that precedes the keyword interface. This tells the compiler that an annotation
type is being declared. Next, notice the two members str( ) and val( ). All annotations
consist solely of method declarations.
18. How can you retrieve all annotations with the RUNTIME retention policy
associated with an element in Java reflection? Give its syntax.
We can obtain all annotations that have RUNTIME retention that are associated with an
item by calling getAnnotations( ) on that item. It has this general form:
Annotation[ ] getAnnotations( )

19. Name any two commonly used built-in annotations and briefly describe their
purpose?
Two commonly used built-in annotations and briefly describe their purposes are:
The @Override annotation is used to indicate that a method overrides or replaces the
behavior of an inherited method.
@SuppressWarnings indicates we want to ignore certain warnings from a part of the
code.
20. What are some key characteristics of a Java Bean?
Some key characteristics of a Java Bean are:
 A Java Bean is a software component that has been designed to be reusable in
a variety of different environments. There is no restriction on the capability of
a Bean. It may perform a simple function, such as obtaining an inventory
value, or a complex function, such as forecasting the performance of a stock
portfolio.
 A Bean may be visible to an end user. One example of this is a button on a
graphical user interface. A Bean may also be invisible to a user.

21. List two advantages of Java Beans


Two advantages of Java Beans:
• A Bean obtains all the benefits of Java’s “write-once, run-anywhere” paradigm.
•The properties, events, and methods of a Bean that are exposed to another
application can be controlled.

22. Why is introspection essential for Java Beans technology?


Introspection is the process of analyzing a Bean to determine its capabilities. This is
an essential feature of the Java Beans API because it allows another application, such
as a design tool, to obtain information about a component. Without introspection, the
Java Beans technology could not operate.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 6

23. What is the difference between a simple property and an indexed property?
 A simple property has a single value. It can be identified by the following
design patterns,
where N is the name of the property and T is its type:
public T getN( )
public void setN(T arg)
 An indexed property consists of multiple values. It can be identified by the
following design patterns, where N is the name of the property and T is its type:
public T getN(int index);
public void setN(int index, T value);
public T[ ] getN( );
public void setN(T values[ ]);

24. What are the two main components used to define a simple property in a
Java Bean. Briefly explain their roles.
The two main components used to define a simple property in a Java Bean are:
public T getN( )
public void setN(T arg)
A read/write property has both of these methods to access its values. A read-only
propertyhas only a get method. A write-only property has only a set method.

25. What are the key differences between bound properties and constrained
properties in Java Beans?
 A Bean that has a bound property generates an event when the property is
changed. The event is of type PropertyChangeEvent and is sent to objects
that previously registered an interest in receiving such notifications. A class
that handles this event must implement the PropertyChangeListener
interface.
 A Bean that has a constrained property generates an event when an attempt is
made to change its value. It also generates an event of type
PropertyChangeEvent. It too is sent to objects that previously registered an
interest in receiving such notifications.
26. What is persistence in JavaBeans?
Persistence is the ability to save the current state of a Bean, including the values of a
Bean’s properties and instance variables, to nonvolatile storage and to retrieve them
at a later time.
The object serialization capabilities provided by the Java class libraries are used to
provide persistence for Beans.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 7

27. What are customizers?


A customizer in Java Bean is a user interface that is used to customize the properties
of a JavaBean. A customizer can provide a step-by-step guide through the process
that must be followed to use the component in a specific context. A Bean developer
has great flexibility to develop a customizer that can differentiate his or her product
in the marketplace.

Unit-2 (2 marks)
1. What is collection Framework? List any two goals of collection Framework.
The Collections Framework is a sophisticated hierarchy of interfaces and classes that
provide state-of-the-art technology for managing groups of objects.
Any two goals of collection Framework
 The framework had to be high-performance. The implementations for the
fundamental collections (dynamic arrays, linked lists, trees, and hash tables) are
highly efficient.
 The framework had to allow different types of collections to work in a similar
manner and with a high degree of interoperability.

2. What are the benefits of using the Collections Framework?


 Reduced programming effort: Provides data structures and algorithms,
eliminating the need to write them manually.
 Increased performance: Offers high-performance implementations of data
structures and algorithms.
 Code reusability: Reduces coding lines and provides a reliable way to reuse code.
 Consistent API: Provides a basic set of interfaces like Collection, Set, List, or
Map, with common methods across all implementing classes.

3. List any two collection classes with its purpose.

4. Write the differences between hasNext() and next() method.


Feature hasNext() next()

Return type Boolean Object


VI SEMESTER BCA Advanced Java and J2EE Question Bank 8

Return value True if there are more elements, The next element in the
false if there are no more collection
elements

Usage Checks if there are any Returns the next element of


remaining elements in a list a collection

Moves the iterator No Yes

5. What is map? List any two Map interface


 A map is an object that stores associations between keys and values, or
key/value pairs. Given a key, you can find its value. Both keys and values are
objects.
Map interfaces:

6. Write the purpose of Array class.


The Arrays class in Java provides static methods to dynamically create and access
Java arrays. It consists of only static methods and the methods of Object class. The
methods of this class can be used by the class name itself.
The Arrays class provides methods for performing common operations on arrays,
such as sorting, searching, filling, and comparing. It also provides methods for
converting arrays to and from other data structures, such as lists and strings.

7. Write the purpose of


a. fill()
b. copyOf()

8. Write the usage of iterator interface.


An iterator offers a general-purpose, standardized way of accessing the elements
within a collection, one at a time. Thus, an iterator provides a means of enumerating
the contents of a collection. Because each collection implements Iterator, the
VI SEMESTER BCA Advanced Java and J2EE Question Bank 9

elements of any collection class can be accessed through the methods defined by
Iterator.
9. List any four interfaces provided by Collection Framework.
Four interfaces provided by Collection Framework:
Collection, List, Comparator, Queue, ListIterator, DQueue, Map,Set
10. Write any two uses of Generics.
Two uses of Generics
 Generics add the one feature that collections had been missing: type safety. Prior
to generics, all collections stored Object references, which meant that any
collection could store any type of object.
 With generics, it is possible to explicitly state the type of data being stored, and
run-time type mismatch errors can be avoided.
11. List any four exceptions thrown in the context of collections.
Four Exceptions in the context of collections:
 Several methods can throw an UnsupportedOperationException, if a
collection cannot be modified.
 A ClassCastException is generated when one object is incompatible with
another, such as when an attempt is made to add an incompatible object to a
collection.
 A NullPointerException is thrown if an attempt is made to store a null object
and null elements are not allowed in the collection.
 An IllegalArgumentException is thrown if an invalid argument is used.
 An IllegalStateException is thrown if an attempt is made to add an element
to a fixed-length collection that is full.
12. What is the usage of containsAll() and retainAll() methods?
The usage of containsAll() is to determine whether one collection contains all the
members of another, and retainAll() method will remove all elements except those
of a specified group by calling retainAll( ).

13. List any four methods of List interface.


VI SEMESTER BCA Advanced Java and J2EE Question Bank 10

14. What is the purpose of the NavigableSet interface in the Java Collections
Framework.
NavigableSet extends SortedSet and declares the behavior of a collection that
supports the retrieval of elements based on the closest match to a given value or
values.
NavigableSet is a generic interface that has this declaration:
interface NavigableSet <E>.

15. How you can add or remove element to/from the first, last using LinkedList
Class.
o To add elements to the start of a list you can use addFirst( ) or offerFirst( ).
o To add elements to the end of the list, use addLast( ) or offerLast( ). To obtain
the first element, you can use getFirst( ) or peekFirst( ).
o To obtain the last element, use getLast( ) or peekLast( ). To remove the first
element, use removeFirst( ) or pollFirst( ).
o To remove the last element, use removeLast( ) or pollLast( ).

16. Differentiate headset() and tailset() methods.


 If you need the subset that starts with the first element in the set, use headSet( ).
If you want the subset that ends the set, use tailSet( ).
VI SEMESTER BCA Advanced Java and J2EE Question Bank 11

17. Differentiate poll() and remove() methods of Queue interface.

18. List any four methods of deque interface.

19. What is the purpose of push() and pop() methods of Deque interface?

20. How does an ArrayList differ from standard arrays?


In Java, standard arrays are of a fixed length. After arrays are created, they cannot
grow or shrink, which means that you must know in advance how many elements an
array will hold.
an ArrayList is a variable-length array of object references. That is, an ArrayList can
dynamically increase or decrease in size. Array lists are created with an initial size.
When this size is exceeded, the collection is automatically enlarged.
21. What are the syntax/signatures of the two overloaded toArray() methods in
the ArrayList class?
Syntax/signatures of the two overloaded toArray() methods in the ArrayList class are:
Object[ ] toArray( )
<T> T[ ] toArray(T array[ ])
VI SEMESTER BCA Advanced Java and J2EE Question Bank 12

The first returns an array of Object. The second returns an array of elements that have
the same type as T. Normally, the second form is more convenient because it returns
the proper type of array.
22. What is the difference between the HashSet() and HashSet(int capacity)
constructors?
 HashSet( )- constructs a default hash set
 HashSet(int capacity)- initializes the capacity of the hash set to capacity. (The
default capacity is 16.)

23. What is the purpose of the float fillRatio parameter in the HashSet(int
capacity, float fillRatio) constructor?
HashSet(int capacity, float fillRatio)-initializes both the capacity and the fill ratio
(also called loadcapacity) of the hash set from its arguments.
The fill ratio must be between 0.0 and 1.0, and it determines how full the hash
set can be before it is resized upward. Specifically, when the number of elements is
greater than the capacity of the hash set multiplied by its fill ratio, the hash set is
expanded. For constructors that do not take a fill ratio, 0.75 is used.

24. What is the primary advantage of using a TreeSet over other Set
implementations like HashSet?
The primary advantage of using a TreeSet over other Set implementations like
HashSet are:
TreeSet extends AbstractSet and implements the NavigableSet interface. It creates a
collection that uses a tree for storage. Objects are stored in sorted, ascending order.
Accessand retrieval times are quite fast, which makes TreeSet an excellent choice
when storing large amounts of sorted information that must be found quickly.
25. What is the main difference between using a foreach loop and an Iterator to
traverse the elements of a Collection in Java?
The main difference between using a foreach loop and an Iterator to traverse the
elements of a Collection in Java is that a foreach loop hides the Iterator
implementation, while an Iterator provides more control over the traversal. We cann
not modify the collection in for each loop, but can modify in Iterator.

26. What is the purpose of the RandomAccess interface in Java collections?


The purpose of the RandomAccess interface in Java collections is to it support
efficient random access to its elements. The RandomAccess interface contains no
members. However, by implementing this interface, a collection signals that although
a collection might support random access, it might not do so efficiently. By checking
VI SEMESTER BCA Advanced Java and J2EE Question Bank 13

for the RandomAccess interface, client code can determine at run time whether a
collection is suitable for certain types of random access operations—especially as
they apply to large collections.
27. How does a Map differ from a Collection in Java?
A Map is a structure that has unique keys mapping to values. A Collection is just a
grouping of multiple values with no specific key.

28. List any four Map classes

29. What is the purpose of using a Comparator with TreeSet and TreeMap in
Java?
The purpose of using a Comparator with TreeSet and TreeMap in Java are:
 By default, these classes store their elements by using what Java refers to as
“natural ordering,” which is usually the ordering that we would expect.
 If we want to order elements in a different way, then specify a Comparator
when we construct the set or map.
 Doing so gives us the ability to govern precisely how elements are stored
within sorted collections and maps.

30. List any four overloaded forms/signatures of the binarySearch() method with
their proper syntax.

31. Differentiate Vector and Arrays


Vector implements a dynamic array. Vector is synchronized, and it contains many
legacy methods that are not part of the Collections Framework. With the advent of
collections, Vector was reengineered to extend AbstractList and to implement the
List interface. With the release of JDK 5, it was retrofitted for generics and
VI SEMESTER BCA Advanced Java and J2EE Question Bank 14

reengineered to implement Iterable. This means that Vector is fully compatible with
collections, and a Vector can have its contents iterated by the enhanced for loop.

32. What is the relationship between the Dictionary class and the Map interface
in Java?
The Map interface is a replacement for the Dictionary abstract class, which is
considered obsolete. New code usually will use a Map instead. Older and legacy
code, however, uses Dictionary, and some implementations of the Map interface also
use Dictionary. For example, Hashtable extends Dictionary and implements Map.

33. What are two advantages of using the MVC architecture in Java
applications?
 Separation of Concerns: MVC promotes a clear separation of concerns
between the model, view, and controller components. This separation allows
for better code organization, improved modularity, and easier maintenance.
 Code Reusability: By separating the concerns into distinct components,
code reuse becomes more feasible. The model can be reused across different
views, and multiple views can be created for a single model.
34. What is Model-View-Controller?
The Model-View-Controller (MVC) architecture in Java is a design pattern that
provides a structured approach for developing applications. It separates the
application’s concerns into three main components: the model, the view, and the
controller. Each component has a specific role and responsibility within the
architecture.

35. What are two responsibilities of the View component in MVC?


The view is responsible for rendering the user interface and displaying the data to
the user. It presents the data from the model to the user in a visually appealing and
understandable way. The view component does not contain any business logic but
instead relies on the model for data.

36. What are the primary roles of the Controller component in the MVC
architecture?
The controller acts as an intermediary between the model and the view. It
handles user input, processes user actions, and updates the model or view
accordingly. The controller interprets user actions and triggers the appropriate
methods in the model or view. It ensures the separation of concerns by keeping
the view and model independent of each other.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 15

37. What are the responsibilities of the Model component in handling data and
business logic?
The model represents the data and business logic of the application. It encapsulates
the application’s data and provides methods for accessing, manipulating, and
updating that data. The model component is independent of the user interface and
focuses solely on the application’s functionality.

Unit-3 (2 marks)
1. Write the any two differences between StringBuffer and StringBuilder class.
1. Thread Safety:
 StringBuffer:
Methods are synchronized, making it thread-safe. Multiple threads can access
and modify the StringBuffer object concurrently without causing data corruption.
 StringBuilder:
Methods are not synchronized, making it non-thread-safe. Concurrent access
from multiple threads may lead to unpredictable behavior and data corruption.
2. Performance:
 StringBuffer:
Due to synchronization overhead, StringBuffer is slower than StringBuilder.
 StringBuilder:
Absence of synchronization makes it faster and more efficient than
StringBuffer.

2. Write the purpose of + operator in string handling with an example.


The + operator concatenates two strings, producing a String object as the result.
For example, the following fragment concatenates three strings:
String age = "21";
String s = "He is " + age + " years old.";
System.out.println(s);
This displays the string “He is 21 years old.”

3. Write two ways to create a String object using the String constructors, and
provide an example for each.
1. The String literal constructor is the most common way to create a String object. It
takes a string literal as its argument and returns a new String object that contains the
same characters as the string literal.
Ex: String s=”Hello Java”;
VI SEMESTER BCA Advanced Java and J2EE Question Bank 16

2. The new keyword can be used to create a new String object from a variety of
sources, including an array of characters, a byte array, or another String object.
Ex: String s=new String(“Hello Java”);

4. What is the purpose of the toString() method in the context of strings.


toString() method simply return a String object that contains the human-readable
string that appropriately describes an object of your class.
By overriding toString( ) for classes that we create, allow them to be fully integrated
into Java’s programming environment. For example, they can be used in print( ) and
println( ) statements and in concatenation expressions.

5. How to initialize String objects using string literals?


The String literal constructor is the most common way to create a String object. It
takes a string literal as its argument and returns a new String object that contains the
same characters as the string literal.
We initialize String objects using string literals in the following way:
String s2 = "abc";

6. What are the different ways to extract individual characters from a string?
Give the syntax.
The different ways to extract individual characters from a string:
charAt( )
To extract a single character from a String, you can refer directly to an individual
character via the charAt( ) method. It has this general form:
char charAt(int where)
Here, where is the index of the character that you want to obtain. The value of where
must be nonnegative and specify a location within the string.
7. Provide the syntax and an example for the charAt() method to extract
characters from a string.
charAt( ) returns the character at the specified location. For example,
char ch;
ch = "abc".charAt(1);
assigns the value “b” to ch.
getChars( )

8. Write the purpose and syntax of the regionMatches() method in string


handling.
The regionMatches( ) method compares a specific region inside a string with another
specific
VI SEMESTER BCA Advanced Java and J2EE Question Bank 17

region in another string. There is an overloaded form that allows you to ignore case in
such comparisons. Here are the general forms for these two methods:
boolean regionMatches(int startIndex, String str2,int str2StartIndex, int
numChars)
boolean regionMatches(boolean ignoreCase,int startIndex, String str2,int
str2StartIndex, int numChars)

9. Demonstrate the usage of the startsWith() and endsWith() methods in string


handling.
The startsWith( ) method determines whether a given String begins with a specified
string.
Conversely, endsWith( ) determines whether the String in question ends with a
specified
string. They have the following general forms:
boolean startsWith(String str)
boolean endsWith(String str)
Here, str is the String being tested. If the string matches, true is returned. Otherwise,
false
is returned. For example,
"Foobar".endsWith("bar")
and
"Foobar".startsWith("Foo")
are both true.

10. What's the difference between equals() and == ?


The equals( ) method and the == operator perform two different operations. As just
explained, the equals( ) method compares the characters inside a String object. The
== operator compares two object references to see whether they refer to the same
instance. The following program shows how two different String objects can contain
the same characters, but references to these objects will not compare as equal:

11. Describe the functionalities of the indexOf and lastIndexOf methods used for
string manipulation.
• indexOf( ) Searches for the first occurrence of a character or substring.
• lastIndexOf( ) Searches for the last occurrence of a character or substring.

12. What are the two forms of the substring() method and what do their
arguments represent?
substring( )
VI SEMESTER BCA Advanced Java and J2EE Question Bank 18

We can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin.
 This form returns a copy of the substring that begins at startIndex and runs to
the end of the invoking string.
 The second form of substring( ) allows you to specify both the beginning and
ending index of the substring:
String substring(int startIndex, int endIndex)
Here, startIndex specifies the beginning index, and endIndex specifies the stopping
point.

13. Describe the two forms of the replace() method and their functionalities.
 The first replaces all occurrences of one character in the invoking string with
another character. It has the following general form:
String replace(char original, char replacement)
 The second form of replace( ) replaces one character sequence with another. It
has this
general form:
String replace(CharSequence original, CharSequence replacement)

14. What is the purpose of the valueOf() method in Java and how does it relate
to the toString() method?
 The valueOf() method is a static method, while the toString() method is a non-
static method. This means that the valueOf() method can be called without
creating an instance of the String class, while the toString() method can only be
called on an instance of an object.
 The valueOf() method can be used to convert any data type to a string, while
the toString() method can only be used to convert objects to strings.

15. How does StringBuffer differ from String in terms of mutability and
growth?
String represents fixed-length, immutable character sequences. In contrast,
StringBuffer represents growable and writeable character sequences. StringBuffer
may have characters and substrings inserted in the middle or appended to the end.
StringBuffer will automatically grow to make room for such additions and often has
more characters preallocated than are actually needed, to allow room for growth.
16. What is the purpose of the ensureCapacity() method in StringBuffer? Give
its general form.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 19

ensureCapacity( )
If you want to preallocate room for a certain number of characters after a
StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the
buffer. This is useful if you know in advance that you will be appending a large
number of small strings to a StringBuffer. ensureCapacity( ) has this general form:
void ensureCapacity(int capacity)

17. How does the setLength() method modify the length of a StringBuffer and
what happens to existing data when the length is changed?
We can modify the length of a StringBuffer using void setLength(int len). Here, len
specifies the length of the buffer. This value must be nonnegative. When you increase
the size of the buffer, null characters are added to the end of the existing buffer. If
you call setLength( ) with a value less than the current value returned by length( ),
then the characters stored beyond the new length will be lost.
18. What do the charAt() and setCharAt() methods do in StringBuffer?
char charAt(int where)
void setCharAt(int where, char ch)
For charAt( ), where specifies the index of the character being obtained. For
setCharAt( ), where specifies the index of the character being set, and ch specifies the
new value of that character. For both methods, where must be nonnegative and must
not specify a location beyond the end of the buffer.

19. What does the append() method do in StringBuffer? Which function is called
for each parameter to obtain its string representation?
The append( ) method concatenates the string representation of any other type of data
to the end of the invoking StringBuffer object. It has several overloaded versions.
Here are a few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
String.valueOf( ) is called for each parameter to obtain its string representation. The
result is appended to the current StringBuffer object.
20. What does the insert() method do in StringBuffer and how is it different
from append()?
The insert( ) method inserts one string into another. It is overloaded to accept values
of all the simple types, plus Strings, Objects, and CharSequences.
The append( ) method concatenates the string representation of any other type of data
to the end of the invoking StringBuffer object.
21. How does StringBuilder differ from StringBuffer?
Refer 1st question.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 20

22. What are the roles of the Stub and Skeleton objects in RMI?
The communication between client and server is handled by using two
intermediate objects: Stub object (on client side) and Skeleton object (on server-
side) as also can be depicted from below media as follows

23. What is RMI?


The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an
object running in another JVM.
24. What is Syntactic transparency?
 Syntactic transparency: This implies that there should be a similarity
between the remote process and a local procedure.

25. What is Semantic transparency?


 Semantic transparency: This implies that there should be similarity in the
semantics i.e. meaning of a remote process and a local procedure.
26. What are the requirements for a class to be serializable?
The requirements for a class to be serializable are
 Implement the Serializable interface
The java.io.Serializable interface is a marker interface with no methods or
fields to implement. To implement it, add the clause implements Serializable to the
class declaration.
 Ensure all fields are serializable
If a serializable class has an array of objects, all the objects in the array must
also be serializable. Otherwise, a NotSerializableException will be thrown.

27. State two advantages of using distributed computing over centralized co


mputing .
Scalability: Distributed systems are generally more scalable than centralized
VI SEMESTER BCA Advanced Java and J2EE Question Bank 21

systems, as they can easily add new devices or systems to the network to increase
processing and storage capacity.
Reliability: Distributed systems are often more reliable than centralized systems, as
they can continue to operate even if one device or system fails.
Flexibility: Distributed systems are generally more flexible.

28. State any four key characteristics that define a distributed computing
system.
 Multiple Devices or Systems: Processing and data storage is distributed
across multiple devices or systems.
 Peer-to-Peer Architecture: Devices or systems in a distributed system can
act as both clients and servers, as they can both request and provide services
to other devices or systems in the network.
 Shared Resources: Resources such as computing power, storage, and
networking are shared among the devices or systems in the network.
 Horizontal Scaling: Scaling a distributed computing system typically
involves adding more devices or systems to the network to increase
processing and storage capacity.

29. List the elements used in the working of RPC.


There are 5 elements used in the working of RPC:

 Client
 Client Stub
 RPC Runtime
 Server Stub
 Server

30. Why is the RMI Registry important in Remote Method Invocation (RMI)
applications?
RMI registry is a namespace on which all server objects are placed. So it is
important when each time the server creates an object, it registers this object
with the RMIregistry (using bind() or reBind() methods). These are registered
using a unique name known as bind name. It allows remote clients to get a
reference to these objects.

31. Write any two limitations of distributed computing.


 Complexity: Distributed systems can be more complex than centralized
systems, as they involve multiple devices or systems that need to be
VI SEMESTER BCA Advanced Java and J2EE Question Bank 22

coordinated and managed.


 Security: It can be more challenging to secure a distributed system, as
security measures must be implemented on each device or system to ensure
the security of the entire system.

32. When does RMI callback occur?


An RMI callback occurs when the client of one service passes an object that is
the proxy for another service. The recipient can then call methods in the object it
received, and be calling back (hence the name) to where it came from.

Unit-4 (2 marks)
1. What are servlets?
Servlets are small programs that execute on the server side of a web connection. Just
as applets dynamically extend the functionality of a web browser, servlets
dynamically extend the functionality of a web server.

2. List the drawbacks of CGI programs.


It was expensive in terms of processor and memory resources to create a separate
process for each client request.
It was also expensive to open and close database connections for each client request.
In addition, the CGI programs were not platform-independent.

3. List the advantages of servlet.


 First, performance is significantly better. Servlets execute within the address
space of a web server. It is not necessary to create a separate process to handle
each client request.
 Second, servlets are platform-independent because they are written in Java.
 Third, the Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine.

4. With syntax write the purpose of getParameter() method.


getParameter() method in getting data, especially form data, from a client HTML
page to a JSP page is dealt with here. The request.getParameter() is being used
here to retrieve form data from client side.
<input type="text" name="ename">--HTML
String val = request.getParameter("ename");--JSP
VI SEMESTER BCA Advanced Java and J2EE Question Bank 23

5. What is the purpose of extending the GenericServlet class in the servlet, and
what methods does it provide by default?
The GenericServlet class provides functionality that simplifies the creation of a
servlet. For example, it provides versions of init( ) and destroy( ), which may be used
as is. You need supply only the service( ) method.

6. Explain the role of the ServletRequest and ServletResponse objects in the


service() method.
ServletRequest object enables the servlet to read data that is provided via the client
request. The ServletResponse object enables the servlet to formulate a response for
the client.

7. What is ServletConfig Interface? Mention any 2 methods.


Servlet interface declares life cycle methods for a servlet and ServletConfig
interface allows servlets to get initialization parameters.

8. What is the purpose and significance of the getWriter() method in the context
of generating an HTTP response in a servlet?
getWriter :Returns a PrintWriter object that can send character text to the client. in
this case, the servlet binded with the url-pattern (previously set) is called. The method
being called depends on the kind of request (doGet, doPost, doPut).

9. _Servlet interface declares life cycle methods for a servlet and ServletConfig
interface allows servlets to get initialization parameters.

10. What is the role of the getServletConfig() and getServletInfo() methods in the
Servlet interface.
The getServletConfig( ) method is called by the servlet to obtain initialization
parameters. A servlet developer overrides the getServletInfo( ) method to provide a
string with useful information (for example, author, version, date, copyright).
This method is also invoked by the server.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 24

11. Differentiate between the getInitParameter(String param) and


getInitParameterNames() methods in the ServletConfig interface.

12. What the purpose and usage of the getAttribute(String attr) and
setAttribute(String attr, Object val) methods in the ServletContext interface.

13. What is the purpose of the getParameterNames() and


getParameterValues(String name) methods in the ServletRequest interface.

14. What is the usage of readLine(byte[] buffer, int offset, int size) method in the
ServletInputStream class?.
readLine(byte [ ] b, int offset, int len):It is a part of ServletInputStream class. It is
used to read the input stream. It will return a number of bytes read or -1. It might
throw IOException if an input or output exception occurs.

15. What's the specific purpose of ServletOutputStream and


ServletInputStream?
ServletOutputStream class is a component of Java package javax.servlet, is an
abstract class that provides an output stream to send binary data to the client.
ServletOutputStream inherits OutputStream which is the superclass of all
classes representing an output stream of bytes. Subclasses of
ServletOutputStream class must implement the java.io.OutputStream.write(int)
method.

16. List classes that are provided in the javax.servlet.http package


Classes in javax. servlet. http package
 HttpServlet.
 Cookie.
 HttpServletRequestWrapper.
 HttpServletResponseWrapper.
 HttpSessionEvent.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 25

 HttpSessionBindingEvent.

17. Write the usage of any two methods described in the HttpServletResponse
interface.
1. sendRedirect(String location): This method redirects the client to a new URL
specified by the location parameter.
2. setStatus(int statusCode): This method sets the HTTP status code of the
response. Common status codes include:
 200 OK: The request was successful.
 404 Not Found: The requested resource could not be found.
 500 Internal Server Error: An unexpected error occurred on the server.

18. What is Cookie? How it is helpful?


Cookies are small text files that websites send to your browser when you visit
them. They help websites remember information about you, which can make your
experience more convenient and personal. Cookies can be used for many purposes,
including:
 Personalization
 Session management
 E-commerce

19. Describe the significance of the valueBound and valueUnbound methods in
the HttpSessionBindingListener interface.
valueBound(HttpSessionBindingEvent event) Notifies the object that it is being
bound to a session and identifies the session.
valueUnbound(HttpSessionBindingEvent event) Notifies the object that it is being
unbound from a session and identifies the session.

20. What information can be stored in a cookie?


Some of the information that is saved for each cookie includes the following:
• The name of the cookie
• The value of the cookie
• The expiration date of the cookie
• The domain and path of the cookie
VI SEMESTER BCA Advanced Java and J2EE Question Bank 26

21. What is the significance of the getSession( ) method of HttpServletRequest?


The getSession() method of HttpServletRequest is a key method for developers to
interact with user sessions. It allows developers to retrieve an existing session or
create a new one if one doesn't already exist. This method is central to session
management, providing a simple way to handle user-specific data and interactions.

22. Write the purpose of next() and getString().


The next() method of the ResultSet interface moves the pointer of the current
(ResultSet) object to the next row, from the current position.
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select * from MyPlayers");
rs.next();

The getString() method in Java is used to retrieve the value of a column in a


ResultSet object as a String. The ResultSet object is a data structure that is used to
store the results of a database query.

23. List the parts of URL that is used in getConnection() method to establish
connection.
The parts of URL that is used in getConnection() method to establish connection
getConnection(String url, String user, String password)
String url = "jdbc:odbc:CustomerInformation";

24. Write the purpose of setLoginTimeout() and getLoginTimeout()


The setLoginTimeout() method of Java DriverManager class sets the maximum time
in seconds that a driver can wait while attempting logging in to the database.
Syntax: public static void setLoginTimeout(int seconds)
The getLoginTimeout() method of Java DriverManager class gets the maximum
time in seconds that a driver can wait while attempting logging in to the database.
Syntax: public static int getLoginTimeout()

25. Write the purpose of forName() and createStatement().


The Class.forName() method is used to load the JDBC driver. Suppose a developer
wants to work offline and write a J2EE application that interacts with Microsoft
Access on the developer’s PC. The developer must write a routine that loads the
JDBC/ODBC Bridge driver called sun.jdbc.odbc.JdbcOdbcDriver. The driver is
loaded by calling the Class.forName() method and passing it the name of the driver,
as shown in the following code segment:
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
VI SEMESTER BCA Advanced Java and J2EE Question Bank 27

The Connect.createStatement() is used to create a Statement object. The Statement


object is then used to execute a query and return a ResultSet object that contains the
response from the DBMS, which is usually one or more rows of information
requested by the J2EE application.

27. What is the main purpose of the JDBC to ODBC (Type 1) driver?
The JDBC to ODBC driver, also called the JDBC/ODBC Bridge, is used to translate
DBMS calls between the JDBC specification and the ODBC specification. The JDBC
to ODBC driver receives messages from a J2EE application that conforms to the
JDBC specification. Those messages are translated by the JDBC to ODBC driver into
the ODBC message format, which is then translated into the message format
understood by the DBMS.

28. Differentiate between Type 3 and Type 4 JDBC drivers. Which one is
considered to be the fastest way to communicate SQL queries to the DBMS?
Type 3 JDBC Driver
The Type 3 JDBC driver, also referred to as the Java Protocol, is the most commonly
used JDBC driver. The Type 3 JDBC driver converts SQL queries into JDBC-
formatted statements. The JDBC-formatted statements are translated into the format
required by the DBMS.
Type 4 JDBC Driver
The Type 4 JDBC driver is also known as the Type 4 Database Protocol. This driver
is similar to the Type 3 JDBC driver, except SQL queries are translated into the
format required by the DBMS. SQL queries do not need to be converted to JDBC-
formatted systems. This is the fastest way to communicate SQL queries to the
DBMS.

29. What is the difference between the executeQuery() and executeUpdate()


methods of a Statement object in JDBC?
The executeQuery() method returns one ResultSet object that contains rows,
columns, and metadata that represent data requested by the query. The ResultSet
object also contains methods that are used to manipulate data in the ResultSet.
The executeUpdate() method is used to execute queries that contain UPDATE and
DELETE SQL statements, which change values in a row and remove a row,
respectively. The executeUpdate() method returns an integer indicating the number of
rows that were updated by the query. ExecuteUpdate() is used to INSERT, UPDATE,
DELETE, and DDL statements.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 28

30. Briefly explain what a ResultSet object represents in JDBC.


The SQL statements that read data from a database query, return the data in a result
set. The SELECT statement is the standard way to select rows from a database and
view them in a result set. The java.sql.ResultSet interface represents the result set of a
database query.

A ResultSet object maintains a cursor that points to the current row in the result set.
The term "result set" refers to the row and column data contained in a ResultSet
object.

31. What is the main advantage of using a PreparedStatement object over a


Statement object in JDBC?

1. PreparedStatement in Java allows you to write a parameterized query that gives


better performance than the Statement class in Java.

2. In the case of PreparedStatement, the Database uses an already compiled and


defined access plan, this allows the prepared statement query to run faster than a
normal query.

32. How do PreparedStatement objects handle dynamic values in SQL queries?

Instead of hardcoding queries like,


select * from students where age>10 and name ='Chhavi'
Set parameter placeholders(use question mark for placeholders) like,
select * from students where age> ? and name = ?
PreparedStatement myStmt;
myStmt = myCon.prepareStatement(select * from students where age> ? and name
= ?);
3. Set parameter values for type and position
myStmt.setInt(1,10);
myStmt.setString(2,"Chhavi");
4. Execute the Query
ResultSet myRs= myStmt.executeQuery();

33. What are the different parameters used by CallableStatement object?

The CallableStatement object uses three types of parameters when calling a stored
procedure. These parameters are IN, OUT, and INOUT.
VI SEMESTER BCA Advanced Java and J2EE Question Bank 29

The IN parameter contains any data that needs to be passed to the stored procedure
and whose value is assigned using the setXXX() method, as described in the previous
section.

The OUT parameter contains the value returned by the stored procedures, if any. The
OUT parameter must be registered using the registerOutParameter() method and then
is later retrieved by the J2EE application using the getXXX() method.

The INOUT parameter is a single parameter used for both passing information to the
stored procedure and retrieving information from a stored procedure using the
techniques described in the previous two paragraphs.

34. How to Insert a Row in to the ResultSet.

Inserting a row into the ResultSet is accomplished using basically the same technique
used to update the ResultSet. That is, the updateXXX() method is used to specify the
column and value that will be placed into the column of the ResultSet.

You can insert one or multiple columns into the new row using the same technique.
The updateXXX() method requires two parameters. The first parameter is either the
name of the column or the number of the column of the ResultSet. The second
parameter is the new value that will be placed in the column of the ResultSet.
Remember that the data type of the column replaces the XXX in the method name.

35. Why Savepoints are used in datatabase transaction?

A savepoint, introduced in JDBC 3.0, is a virtual marker that defines the task at
which the rollback stops. In the previous example, the task before the email
confirmation notice is sent can be designated as a savepoint.

A savepoint is created after the execution of the first UPDATE SQL statement. There
can be many savepoints in a transaction; each is identified by a unique name.

36. How to batch sql statement into transaction statement?

We can combine SQL statements into a transaction are to batch statements together
into a single transaction and then execute the entire transaction. You can do this by
using the addBatch() method of the Statement object. The addBatch() method
receives an SQL statement as a parameter and places the SQL statement in the batch.
Once all the SQL statements that make up the transaction are included in the batch,
the executeBatch() method is called to execute the entire batch at the same time. The
VI SEMESTER BCA Advanced Java and J2EE Question Bank 30

executeBatch() method returns an int array that contains the number of SQL
statements executed

37. What are the methods supported by RowSetListener class?

A RowSetListener is a class you define that implements the RowSetListener


interface.

The RowSetListener class must contain three methods, each of which responds to a
particular event occurring in a RowSet. These methods are as follows: public void
cursorMoved(RowSetEvent event) public void rowChanged(RowSetEvent event)
public void rowSetChanged(RowSetEvent event) The cursorMoved() method must
contain logic that reacts to movement of the cursor within the RowSet. Typically, this
method calls ResultSet.getRow() to return the current row of the ResultSet.

38. What is Java Server Pages?

Java Server Pages (JSP) is a technology for developing Web pages


that supports dynamic content. This helps developers insert java code
in HTML pages by making use of special JSP tags, most of which start
with <% and end with %>.
39. List any four advantages of using JSP.
 The dynamic part is written in Java, not Visual Basic or other MS
specific language, so it is more powerful and easier to use.
 It is portable to other operating systems and non- Microsoft Web
servers.
 It is more convenient to write (and to modify!) regular HTML than
to have plenty of println statements that generate the HTML.
 JavaScript can generate HTML dynamically on the client but can
hardly interact with the web server to perform complex tasks like
database access and image processing etc.

40. List any four implicit Objects


VI SEMESTER BCA Advanced Java and J2EE Question Bank 31

41. What is the usage of buffer attribute in JSP?


The buffer attribute specifies the buffering characteristics for the
server output response object.
<%@ page buffer="none" %>

42. What is page Directive?


The page directive is used to provide instructions to the container.
These instructions pertain to the current JSP page. You may code page
directives anywhere in your JSP page. By convention, page directives
are coded at the top of the JSP page.

You might also like