Java MQP Solution
Java MQP Solution
1)
a) Explain any four legacy classes of Java’s Collection
Framework.
I. Vector
- Vector implements a dynamic array that grows as needed to
accommodate new elements.
- It is similar to ArrayList, but with two differences: Vector is
synchronized, and it contains many legacy methods that are
not part of the Collections.
- It implements the List interface.
- Constructors:
Vector( ): creates a default vector, which has an initial
size of 10.
Vector(int size): creates a vector whose initial capacity
is specified by size.
Vector(int size, int incr): creates a vector whose
initial capacity is specified by size and whose increment is
specified by incr. The increment specifies the number of
elements to allocate each time that a vector is resized
upward.
Vector(Collection c): creates a vector that contains the
elements of collection c.
II. Stack
- Stack is a subclass of Vector that implements a standard
LIFO data structure.
- Stack only defines the default constructor, which creates an
empty stack.
- Stack includes all the methods defined by Vector
III. Dictionary
- Dictionary is an abstract class that represents a key/value
storage repository.
- Given a key and value, you can store the value in a
Dictionary object.
- Once the value is stored, you can retrieve it by using its key.
Thus, like a map, a dictionary can be thought of as a list of
key/value pairs.
IV. Hashtable
- Hashtable was part of the original java.util and is a concrete
implementation of a Dictionary.
- HashMap, Hashtable stores key/value pairs in a hash table.
- However, neither keys nor values can be null.
- When using a Hashtable, you specify an object that is used
as a key, and the value that you want linked to that key.
- The key is then hashed, and the resulting hash code is used
as the index at which the value is stored within the table.
- Constructors:
Hashtable( ): default constructor
Hashtable(int size): creates a hash table that has an
initial size specified by size.
Hashtable(int size, float fillRatio): creates a hash
table that has an initial size specified by size and a fill
ratio specified by fillRatio. If you do not specify a fill ratio,
then 0.75 is used
Hashtable(Map m): creates a hash table that is
initialized with the elements in m. The capacity of the
hash table is set to twice the number of elements in m.
class STUDENT {
private String USN;
private String Name;
@Override
public String toString() {
return "USN: " + USN + ", Name: " + Name;
}
}
2)
a) Explain the methods of NavigableSet class with a sample
program.
- The NavigableSet interface in Java is part of the Java
Collections Framework.
- It extends the SortedSet interface.
- It provides additional methods to navigate and manipulate
the elements in a sorted set.
Methods:
- lower(E e): returns the greatest element in the set that is
strictly less than the specified element.
- floor(E e): returns the greatest element in the set that is
less than or equal to the specified element.
- ceiling(E e): returns the least element in the set that is
greater than or equal to the specified element.
- higher(E e): returns the least element in the set that is
strictly greater than the specified element.
- pollFirst(): retrieves and removes the first (lowest) element
of the set.
- pollLast(): retrieves and removes the last (highest) element
of the set.
import java.util.NavigableSet;
import java.util.TreeSet;
II. addAll
boolean addAll(Collection <? extends E>c): Adds all the
elements of c to the invoking collection. Returns true if the
operation succeeded (i.e., the elements were added).
Otherwise, returns false.
III. clear
void clear(): Removes all elements from the invoking
collection.
IV. contains
boolean contains(Object obj): Returns true if obj is an
element of the invoking collection. Otherwise, it returns false.
V. containsAll
boolean containsAll(Collection c): Returns true if the
invoking collection contains all elements of c. Otherwise, it
returns false.
VI. equals
boolean equals(Object obj): Returns true if the invoking
collection and obj are equal. Otherwise, returns false.
VII. hashCode
int hashCode(): Returns the hash code for the invoking
collection.
VIII. isEmpty
boolean isEmpty(): Returns true if the invoking collection is
empty. Otherwise, it returns false.
IX. iterator
Iterator iterator(): Returns an iterator for the invoking
collection.
X. remove
boolean remove(Object obj): Removes one instance of obj
from the invoking collection. Returns true if the element was
removed. Otherwise, it returns false.
3)
a) List and explain the various String comparison methods.
I. equals( ):
- To compare two strings for equality, use equals( ).
- It has this general form: boolean equals(Object str)
- Here, str is the String object being compared with the
invoking String object.
- It returns true if the strings contain the same characters in
the same order, and false otherwise.
- The comparison is case-sensitive.
II. equalsIgnoreCase( ):
- To perform a comparison that ignores case differences, call
equalsIgnoreCase( ).
- It has this general form: boolean equalsIgnoreCase(String
str)
- Here, str is the String object being compared with the
invoking String object.
- It, too, returns true if the strings contain the same characters
in the same order, and false otherwise.
III. startsWith():
- The startsWith( ) method determines whether a given String
begins with a specified string.
- Syntax: boolean startsWith(String str)
IV. endsWith():
- endsWith( ) determines whether the String in question ends
with a specified string.
- Syntax: boolean endsWith(String str)
V. == :
- The == operator compares two object references to see
whether they refer to the same instance.
VI. compareTo( ):
- It has this general form: int compareTo(String str)
- Here, str is the String being compared with the invoking
String.
class RemoveDuplicatesExample4 {
public static void removeDuplicates(String str) {
String newstr = new String();
int length = str.length();
if (newstr.indexOf(charAtPosition) < 0) {
newstr += charAtPosition;
}
}
System.out.println(newstr);
}
import java.io.UnsupportedEncodingException;
}
}
b) Explain the following methods of StringBuffer class:
i) append(): concatenates the string representation of any
other type of data to the end of the invoking StringBuffer
object. It has several overloaded versions.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
frame.setDefaultCloseOperation(JFrame.EXIT_ON
_CLOSE);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON
_CLOSE);
frame.setSize(300, 200);
frame.setLayout(new BorderLayout());
panel.add(analogButton);
panel.add(digitalButton);
panel.add(analogToggleButton);
panel.add(digitalToggleButton);
analogButton.addActionListener(buttonListener);
digitalButton.addActionListener(buttonListener);
analogToggleButton.addActionListener(buttonListener);
digitalToggleButton.addActionListener(buttonListener);
frame.add(panel, BorderLayout.CENTER);
frame.add(label, BorderLayout.SOUTH);
frame.setVisible(true);
});
}
6)
a) Write a program to create a frame for a simple arithmetic
calculator using swing components and layout managers.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.script.ScriptEngineManager;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 400);
frame.setLayout(new BorderLayout());
display.setHorizontalAlignment(JTextField.RIGHT);
display.setEditable(false);
frame.add(display, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
});
}
}
@Override
public void actionPerformed(ActionEvent e) {
String text = ((JButton)
e.getSource()).getText();
if (text.equals("C")) {
input.setLength(0);
display.setText("");
} else if (text.equals("=")) {
try {
ScriptEngineManager manager = new
ScriptEngineManager();
display.setText(String.valueOf(manager.getEngineByName("J
avaScript").eval(input.toString())));
input.setLength(0);
} catch (Exception ex) {
display.setText("Error");
}
} else {
input.append(text);
display.setText(input.toString());
}
}
}
class EventDemo {
JLabel jlab;
EventDemo() {
JFrame jfrm = new JFrame("An Event Example");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 90);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Alpha was pressed.");
}
});
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jlab.setText("Beta was pressed.");
}
});
jfrm.add(jbtnAlpha);
jfrm.add(jbtnBeta);
7)
a) List and explain the core classes and interfaces in
javax.servlet package.
The javax.servlet package provides the core classes and
interfaces required for building Java web applications.
Interfaces:
- Servlet: Defines methods that all servlets must implement.
- ServletRequest: Defines an object to provide client request
information to a servlet.
- ServletResponse: Defines an object to assist a servlet in
sending a response to the client.
- ServletConfig: A servlet configuration object used by a servlet
container to pass information to a servlet during
initialization.
- ServletContext: Defines a set of methods that a servlet uses to
communicate with its servlet container, for example, to get the
MIME type of a file, dispatch requests, or write to a log file
Classes:
- GenericServlet: Defines a generic, protocol-independent
servlet.
- ServletInputStream: Provides an input stream for reading
binary data from a client request, including an efficient
readLine method for reading data one line at a time.
- ServletOutputStream: Provides an output stream for sending
binary data to the client.
- ServletException: Defines a general exception a servlet can
throw when it encounters difficulty.
- UnavailableException: Defines an exception that a servlet or
filter throws to indicate that it is permanently or temporarily
unavailable.
@WebServlet("/SumServlet")
public class SumServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
int num1 =
Integer.parseInt(request.getParameter("num1"));
int num2 =
Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;
response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>Result</h1>");
response.getWriter().println("<p>Sum: " + sum +
"</p>");
response.getWriter().println("</body></html>");
}
}
<!DOCTYPE html>
<html>
<head>
<title>Sum Calculator</title>
</head>
<body>
<form action="SumServlet" method="get">
<label for="num1">Number 1:</label>
<input type="text" id="num1" name="num1"
required>
<br>
<label for="num2">Number 2:</label>
<input type="text" id="num2" name="num2"
required>
<br>
<input type="submit">
</form>
</body>
</html>
8)
a) Explain different JSP tags with a program to demonstrate all
tags.
JSP tags define java code that is to be executed before the
output of the jsp program is sent to the browser. They are
embedded into the HTML component of a jsp program.
iii. Directive tags: A directive tag opens with <%@ and are
commonly used in directives import, include and taglib
commands.
<!DOCTYPE html>
<html>
<head>
<title>JSP Tag Demo</title>
</head>
<body>
<!-- Declaration -->
<%! int counter = 1; %>
iii. init method is invoked: It calls the init() method when the
servlet instance is loaded. It is used to initialize servlets.
Syntax: public void init(ServletConfig config) throws
ServletException
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("text/html");
response.getWriter().println("<html><body>");
response.getWriter().println("<h1>Stored
Cookies</h1>");
if (cookies != null) {
for (Cookie c : cookies) {
response.getWriter().println("<p>Cookie
Name: " + c.getName() + " | Cookie Value: " +
c.getValue() + "</p>");
}
} else {
response.getWriter().println("<p>No cookies
found.</p>");
}
response.getWriter().println("</body></html>");
}
}
9)
a) What is a statement object in JDBC? Explain the following
statement objects i) Callable statement object ii) Prepared
statement object
Statement object executes query immediately without
precompiling. It contains the executeQuery() method, which
accepts query as argument. Then the query is transmitted for
processing and returns ResultSet as object.
try {
Connection conn =
DriverManager.getConnection(url, username, password);
System.out.println("Connection established
successfully!");
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Using DriverManager:
public class DriverManagerExample {
public static void main(String[] args) {
String url =
"jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";
try {
Connection connection =
DriverManager.getConnection(url, username, password);
System.out.println("Connection established
successfully!");
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
10)
a) Explain the four types of JDBC drivers.
- Types of Connections: