Ad Java QB Solved 2Marks
Ad Java QB Solved 2Marks
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.
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.
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.
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.
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
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.
Return value True if there are more elements, The next element in the
false if there are no more collection
elements
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( ).
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( ).
19. What is the purpose of push() and pop() methods of Deque interface?
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.
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.
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.
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.
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.
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”);
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( )
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)
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
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.
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.
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.
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.
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
12. What the purpose and usage of the getAttribute(String attr) and
setAttribute(String attr, Object val) methods in the ServletContext 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.
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.
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";
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.
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.
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.
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.
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.
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
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.