CS506 – Enterprise Application Development: Midterm Important Subjective (34 Solved Q&As)
Computer Science • Read every solved subjective question with its model answer directly on this page. Free, no login required.
All 664 Midterm Packs · CS506 Course Page · CS506 MCQ Pack (304 MCQs)
-
What is difference between named and anonymous objects? Also give an example for both.
Topic: Java Basics & OOP
Named object: An object that is created and stored in a reference variable (i.e. it has a name) is called a named object. Because a reference to it exists, it can be used again and again anywhere in its scope. Example: Person p = new Person(); — here p is the name/reference of the object, and we can call p.show(); p.display(); etc. any number of times. Anonymous object: An object that is created without assigning it to any reference variable is called an anonymous object. It has no name, so it can be used only at the point where it is created, normally for a single method call. After that statement it becomes unreachable and is eligible for garbage collection. Example: new Person().show(); — the object is created and used for one call only; no reference is kept.
-
The code given below is giving following un-wanted output. Unwanted output: Second employee / Zia / first employee. Explain the reason of this unwanted output and how it can be removed. (Note: in the source screenshot only the unwanted output box is shown; the code itself is not visible.)
Topic: Java Basics & OOP
Reason: This unwanted output is produced because the data member that stores the employee information (name/order) is declared static in the class. A static data member is shared by all objects of the class — there is only one copy of it in memory. So when the second employee object is created, it overwrites the value stored earlier for the first employee. At printing time every object shows the last stored (shared) value, and the output appears disturbed, i.e. "Second employee / Zia / first employee" instead of each employee's own data in proper order. Solution: Remove the static keyword and declare the variable as an instance (non-static) data member. Then every object gets its own separate copy of the variable, each employee keeps its own data, and the output is printed correctly for each object.
-
We cannot pass objects from one system to another but we want to send objects. What modification do we need to do in our class to fulfill our requirement?
Topic: Java Basics & OOP
We need to make the class serializable by implementing the marker interface java.io.Serializable in the class declaration, e.g. public class Student implements java.io.Serializable { ... } Serializable is a marker interface, so no method has to be implemented. After this modification the object can be converted into a byte stream (serialization) using ObjectOutputStream, sent over the network or stored in a file, and reconstructed back into an object (deserialization) on the other system using ObjectInputStream.
-
As we know swing components are called light weight components. But still there are some heavy weight components in swing. Write the names of any four components.
Topic: GUI, AWT/Swing, Applets & Event Handling
Swing components are called lightweight because they are written purely in Java and do not depend on native (operating system) peer components. However, the top-level Swing containers are heavyweight because each of them is backed by a native window/peer. Any four heavyweight components of Swing are: 1. JFrame 2. JApplet 3. JDialog 4. JWindow
-
Override a paintComponent() method to draw empty equilateral triangle using lines and an orange circle over it.
Topic: GUI, AWT/Swing, Applets & Event Handling
public void paintComponent(Graphics g) { super.paintComponent(g); // Empty equilateral triangle drawn with three lines g.drawLine(100, 50, 50, 140); // left side g.drawLine(50, 140, 150, 140); // base g.drawLine(150, 140, 100, 50); // right side // Orange circle drawn over the triangle g.setColor(Color.ORANGE); g.drawOval(75, 70, 50, 50); } Explanation: paintComponent() of JPanel is overridden. drawLine() is used three times to draw the three sides of an empty (unfilled) equilateral triangle, then the drawing colour is set to orange with setColor(Color.ORANGE) and drawOval() draws a circle over the triangle (equal width and height make it a circle).
-
You are required to write code for a GUI based program which will display a button and two labels. First label would contain any text and second label would be empty. By clicking the button first time, the text from the first label will be shifted to second label and first label would become empty. By clicking the button second time, the text from second label will be shifted to first label and second label would become empty and so on.
Topic: GUI, AWT/Swing, Applets & Event Handling
import javax.swing.*; import java.awt.event.*; public class ShiftText extends JFrame implements ActionListener { JButton button = new JButton("Shift"); JLabel label1 = new JLabel("Hello Java"); JLabel label2 = new JLabel(""); public ShiftText() { setLayout(new java.awt.FlowLayout()); add(label1); add(button); add(label2); button.addActionListener(this); setSize(300, 100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void actionPerformed(ActionEvent e) { if (!label1.getText().equals("")) { label2.setText(label1.getText()); label1.setText(""); } else { label1.setText(label2.getText()); label2.setText(""); } } public static void main(String[] args) { new ShiftText(); } } Explanation: On every click of the button, actionPerformed() checks which label currently holds the text. If label1 has the text, it is copied to label2 and label1 is made empty; otherwise the text is copied back from label2 to label1 and label2 is made empty. In this way the text keeps shifting between the two labels on alternate clicks.
-
How the problem of implementing all methods of interface was solved?
Topic: GUI, AWT/Swing, Applets & Event Handling
The problem was solved by introducing adapter classes. When a listener interface contains many methods (e.g. MouseListener has five), a class implementing the interface is forced to provide definitions of all of them even if it needs only one. An adapter class is a class that implements the listener interface and provides empty (blank) implementations of all its methods. The programmer simply extends the adapter class (e.g. MouseAdapter, KeyAdapter, WindowAdapter) and overrides only the method(s) of interest, instead of implementing all the methods of the interface.
-
If we will not write code attribute in applet tag then which one will get true? - Applet will not run - Applet will run but not visible - Applet will run and visible
Topic: GUI, AWT/Swing, Applets & Event Handling
"Applet will not run" is true. The code attribute of the <applet> tag specifies the name of the compiled applet class file (.class) that the browser must load and execute, e.g. <applet code="MyApplet.class" width=200 height=200>. If the code attribute is not written, the browser does not know which class to load, so the applet cannot be started at all — it will neither run nor be displayed.
-
Write a method that gets the coordinate of mouse when it moves and displays them on the screen. Consider JLabel coordinates for displaying coordinates.
Topic: GUI, AWT/Swing, Applets & Event Handling
JLabel coordinates = new JLabel("Move the mouse"); addMouseMotionListener(new MouseMotionAdapter() { public void mouseMoved(MouseEvent e) { coordinates.setText("X: " + e.getX() + " Y: " + e.getY()); } }); Explanation: A MouseMotionListener (through its adapter class MouseMotionAdapter) is registered on the component. Whenever the mouse moves, the mouseMoved() method is automatically called; e.getX() and e.getY() give the current coordinates of the mouse pointer, which are then displayed on the screen through the JLabel by calling setText().
-
You are required to write code for a GUI based program which will display two buttons with some text on them like "Button 1" and "Button 2" respectively. When we will click on any button their text would be swapped with each other.
Topic: GUI, AWT/Swing, Applets & Event Handling
import javax.swing.*; import java.awt.event.*; public class SwapButtons extends JFrame implements ActionListener { JButton b1 = new JButton("Button 1"); JButton b2 = new JButton("Button 2"); public SwapButtons() { setLayout(new java.awt.FlowLayout()); add(b1); add(b2); b1.addActionListener(this); b2.addActionListener(this); setSize(250, 100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void actionPerformed(ActionEvent e) { String temp = b1.getText(); b1.setText(b2.getText()); b2.setText(temp); } public static void main(String[] args) { new SwapButtons(); } } Explanation: The same ActionListener is registered with both buttons, so a click on either button calls actionPerformed(). Inside it, the text of the first button is saved in a temporary variable, the text of the second button is set on the first button, and finally the saved text is set on the second button — hence the texts of both buttons are swapped.
-
In java how we can see the wait time for a statement object to execute?
Topic: JDBC & Databases
The wait time of a Statement object is its query timeout, which is handled through two methods of the java.sql.Statement interface: 1. setQueryTimeout(int seconds) — sets the number of seconds the driver will wait for the statement to execute before timing out. 2. getQueryTimeout() — returns the current wait time (query timeout) in seconds, so by calling stmt.getQueryTimeout() we can see the wait time set for that statement object. A value of 0 means there is no limit, i.e. the statement waits indefinitely.
-
Write a program that shows the following output. 1,2 and so on represents the id's of the students from the table "Students". OUTPUT: Database version: 4.00 / Database Driver: JDBC-ODBC Bridge / Read only: false / 1 ...
Topic: JDBC & Databases
import java.sql.*; public class StudentInfo { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:StudentDSN"); DatabaseMetaData dbmd = con.getMetaData(); System.out.println("Database version: " + dbmd.getDatabaseProductVersion()); System.out.println("Database Driver: " + dbmd.getDriverName()); System.out.println("Read only: " + con.isReadOnly()); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id FROM Students"); while (rs.next()) { System.out.println(rs.getInt(1)); } con.close(); } catch (Exception e) { System.out.println(e); } } } Explanation: The DatabaseMetaData object obtained from con.getMetaData() provides information about the database: getDatabaseProductVersion() gives the database version, getDriverName() gives the driver name (JDBC-ODBC Bridge) and con.isReadOnly() tells whether the connection is read-only. After printing this information, a simple SELECT query on the Students table is executed and the id of every student is printed one by one using rs.next().
-
What is bytecode in Java? What is the role of the JVM, and why is Java called platform independent?
Topic: Java Basics & OOP
When a Java program is compiled, the Java compiler does not produce machine code of any specific machine; instead it produces an intermediate code called bytecode, stored in .class files. Bytecode is a set of instructions for the Java Virtual Machine (JVM), not for a real processor. The JVM is a software that interprets/executes the bytecode on a particular platform. A different JVM is available for every operating system (Windows, Linux, Mac, etc.), but the bytecode remains the same everywhere. Therefore a program is compiled only once and its bytecode can run on any platform that has a JVM — "write once, run anywhere" — which is why Java is called platform independent (at the bytecode level).
-
Differentiate between JDK, JRE and JVM.
Topic: Java Basics & OOP
JVM (Java Virtual Machine): The runtime engine that loads, verifies and executes Java bytecode. It is platform dependent (different for each operating system). JRE (Java Runtime Environment): JVM + library classes and supporting files needed to RUN Java programs. It does not contain development tools like the compiler. JDK (Java Development Kit): JRE + development tools such as the compiler (javac), debugger and documentation tools needed to DEVELOP Java programs. In short: JDK ⊃ JRE ⊃ JVM. To develop programs we install the JDK; to only run programs, the JRE is enough.
-
What are wrapper classes in Java? Why are they used? Give examples.
Topic: Java Basics & OOP
Wrapper classes are the object representations of the primitive data types. Every primitive type has a corresponding class in the java.lang package, e.g. int → Integer, double → Double, char → Character, boolean → Boolean, float → Float, long → Long, byte → Byte, short → Short. They are used when primitive values need to be treated as objects, for example: 1. Collections such as ArrayList and HashMap can store only objects, not primitives, so values are wrapped (e.g. list.add(new Integer(10))). 2. They provide useful utility methods, e.g. Integer.parseInt("123") converts a string into an int. 3. They allow a primitive value to be passed where an Object is required.
-
What is the difference between == operator and equals() method in Java?
Topic: Java Basics & OOP
The == operator compares the values of primitive types, but for objects it compares the references, i.e. it checks whether both references point to the same object in memory. The equals() method is defined in the Object class and is meant to compare the contents of two objects. For example, for String objects, s1.equals(s2) returns true if both strings contain the same sequence of characters, even if they are different objects, whereas s1 == s2 would return false in that case. So: use == for primitives and reference identity, and equals() for comparing the actual contents of objects.
-
What is an ArrayList? How is it different from a normal array, and how is an object retrieved from it?
Topic: Java Basics & OOP
ArrayList is a class of the java.util package that provides a resizable (dynamic) array. Unlike a normal array, whose size is fixed at creation, an ArrayList can grow or shrink as elements are added or removed. Differences from arrays: (1) size is dynamic, not fixed; (2) it stores only objects (wrapper classes are used for primitive values); (3) it provides ready-made methods such as add(), remove(), size() and get(). Objects are added with add() and retrieved with the get(index) method. Because get() returns an Object, it must be cast back to the original type while retrieving, e.g. Person p = (Person) al.get(0);
-
Differentiate between an interface and an abstract class.
Topic: Java Basics & OOP
Interface: (1) Declared with the interface keyword; contains only abstract methods (and constants). (2) A class implements an interface using the implements keyword. (3) A class can implement multiple interfaces, so interfaces support a form of multiple inheritance. (4) All methods are public and abstract by default and no constructor exists. Abstract class: (1) Declared with the abstract keyword; can contain both abstract and concrete (fully defined) methods, instance variables and constructors. (2) A class extends it using the extends keyword. (3) A class can extend only one abstract class. (4) It is used when related classes share some common implemented behaviour along with some unimplemented methods.
-
What is garbage collection in Java? Who performs it?
Topic: Java Basics & OOP
Garbage collection is the automatic process of reclaiming the memory occupied by objects that are no longer reachable/referenced by the program (e.g. anonymous objects after use, or objects whose reference variable has been set to null or gone out of scope). It is performed automatically by the JVM's garbage collector thread. The programmer does not free memory manually as in C/C++; System.gc() can only request/suggest the JVM to run the garbage collector, it cannot force it.
-
What is exception handling in Java? Differentiate between checked and unchecked exceptions, and explain the role of the throws clause.
Topic: Java Basics & OOP
Exception handling is the mechanism of dealing with abnormal/runtime problems (e.g. dividing by zero, file not found, invalid input) in a controlled way so that the program does not crash abruptly. Java provides the try, catch, throw, throws and finally keywords for this purpose: the doubtful code is placed in try, and the handling code in catch. Checked exceptions: Exceptions that are checked by the compiler at compile time, e.g. IOException, SQLException, ClassNotFoundException. The programmer is forced to either handle them with try-catch or declare them with throws; otherwise the program does not compile. Unchecked exceptions: Exceptions that occur at runtime and are not checked by the compiler, e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException. They usually result from programming errors and handling them is optional. throws clause: If a method does not handle a checked exception itself, it declares it in its header, e.g. public void read() throws IOException, which informs the caller that this method may throw that exception and the caller must handle or further declare it.
-
Differentiate between AWT and Swing.
Topic: GUI, AWT/Swing, Applets & Event Handling
1. AWT (Abstract Window Toolkit) components are heavyweight: every component has a native peer supplied by the operating system, so the look and feel depends on the platform. Swing components are lightweight: they are written purely in Java and draw themselves, giving the same look and feel on all platforms. 2. AWT provides a smaller set of components, while Swing provides a much richer set (JTable, JTree, JTabbedPane, etc.). 3. Swing component names start with 'J' (JButton, JLabel), while AWT names do not (Button, Label). 4. Swing supports features like pluggable look and feel and the MVC architecture, which AWT does not.
-
What is an applet? Write down the life cycle methods of an applet in their order of execution.
Topic: GUI, AWT/Swing, Applets & Event Handling
An applet is a small Java program that runs inside a web browser (or applet viewer) and is embedded in an HTML page using the <applet> tag. Unlike a Java application it has no main() method; its execution is controlled by the browser through its life cycle methods. Life cycle methods, in order: 1. init() — called once when the applet is loaded for the first time; used for initialization (like a constructor). 2. start() — called after init() and whenever the user returns to the page containing the applet; the applet becomes active/visible. 3. paint(Graphics g) — called whenever the applet needs to redraw its output on the screen. 4. stop() — called when the user leaves the page containing the applet; the applet becomes inactive. 5. destroy() — called at the end, when the browser closes the applet permanently, to release resources.
-
Explain the delegation event model of Java. Also define event source, event object and event listener.
Topic: GUI, AWT/Swing, Applets & Event Handling
Java handles GUI interactions through the delegation event model, in which the work of handling an event is delegated to a separate listener object instead of being handled by the component itself. It has three participants: 1. Event source: The GUI component that generates the event, e.g. a Button generates an ActionEvent when clicked. 2. Event object: An object that encapsulates all the information about the event that occurred (e.g. ActionEvent, MouseEvent, KeyEvent). It is created by the source and passed to the listener. 3. Event listener: An object that implements the corresponding listener interface (e.g. ActionListener) and provides the handling code in its method (e.g. actionPerformed()). Working: The listener is registered with the source using an addXXXListener() method, e.g. button.addActionListener(listener). When the user interacts with the source, an event object is created and automatically passed to the registered listener's handler method, which executes the required code.
-
What are layout managers in Java? Name and briefly describe any three.
Topic: GUI, AWT/Swing, Applets & Event Handling
A layout manager is an object that controls the size and position of components inside a container automatically, so that the GUI adjusts properly when the window is resized. The layout is set with setLayout(). Three common layout managers are: 1. FlowLayout: Places components in a row, one after another, from left to right; when a row is full, components flow to the next row. It is the default layout of JPanel. 2. BorderLayout: Divides the container into five regions — North, South, East, West and Center — and each component is placed in one region. It is the default layout of JFrame. 3. GridLayout: Divides the container into a grid of equal-sized rows and columns, and every component occupies one cell of the grid.
-
What is a HashMap in Java? How does it store and retrieve values?
Topic: GUI, AWT/Swing, Applets & Event Handling
HashMap is a class of the java.util package that stores data in the form of key–value pairs, where every key is unique and is mapped to exactly one value. Both keys and values are objects. Values are stored with the put(key, value) method and retrieved with the get(key) method by passing the key, e.g. HashMap map = new HashMap(); map.put("id", "123"); String s = (String) map.get("id"); Internally it uses hashing of the key to locate the value quickly, so searching in a HashMap is very fast.
-
What is JDBC? Write down the steps involved in connecting a Java program with a database and retrieving data from it.
Topic: JDBC & Databases
JDBC (Java Database Connectivity) is a Java API (java.sql package) that allows Java programs to connect with databases, execute SQL statements and process the results, independently of the specific database being used. Steps: 1. Load/register the JDBC driver, e.g. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 2. Establish a connection using DriverManager.getConnection(url, user, password), which returns a Connection object. 3. Create a statement object from the connection, e.g. Statement stmt = con.createStatement(); 4. Execute the SQL query and store the result, e.g. ResultSet rs = stmt.executeQuery("SELECT * FROM Students"); 5. Process the ResultSet using rs.next() and getXXX() methods to read each record. 6. Close the ResultSet, Statement and Connection objects to release resources.
-
Differentiate between Statement, PreparedStatement and CallableStatement.
Topic: JDBC & Databases
Statement: Used to execute simple static SQL queries that have no parameters. It is created with con.createStatement() and the query is compiled every time it is executed. PreparedStatement: Used for pre-compiled SQL queries that can take input parameters (represented by '?'). The query is compiled once and can be executed repeatedly with different parameter values, which makes it faster and safer. It is created with con.prepareStatement(sql). CallableStatement: Used to execute stored procedures stored in the database. It is created with con.prepareCall() and can handle IN, OUT and INOUT parameters.
-
Differentiate between executeQuery(), executeUpdate() and execute() methods of the Statement interface.
Topic: JDBC & Databases
executeQuery(sql): Used for SELECT statements. It returns a ResultSet object containing the rows fetched from the database. executeUpdate(sql): Used for INSERT, UPDATE and DELETE statements (and DDL statements). It does not return a ResultSet; it returns an int showing the number of rows affected by the operation. execute(sql): A general-purpose method that can execute any kind of SQL statement (SELECT, INSERT, UPDATE, etc.). It returns a boolean: true if the result is a ResultSet, false if it is an update count.
-
What is a ResultSet in JDBC? How are records traversed and read from it?
Topic: JDBC & Databases
A ResultSet is an object (table-like structure) that holds the data returned by executing a SELECT query through executeQuery(). It maintains a cursor that initially points before the first row. The next() method moves the cursor to the next row and returns true if a row exists, false when the records are finished; therefore records are normally read inside a while (rs.next()) loop. Values of the current row are read with getXXX() methods either by column index or column name, e.g. rs.getInt(1), rs.getString("name"), where XXX is the data type of the column.
-
What is the JDBC-ODBC bridge driver? Also name and briefly describe the four types of JDBC drivers.
Topic: JDBC & Databases
The JDBC-ODBC bridge driver (Type-1) is a driver that translates JDBC calls into ODBC calls, so a Java program can access databases through the already available ODBC drivers. It is supplied with the JDK (sun.jdbc.odbc.JdbcOdbcDriver) and requires ODBC to be configured on the client machine. The four types of JDBC drivers are: 1. Type-1 (JDBC-ODBC Bridge): Converts JDBC calls to ODBC calls; needs ODBC installation on each client. 2. Type-2 (Native-API / partly Java driver): Converts JDBC calls into native (C/C++) database client API calls; requires native libraries on the client. 3. Type-3 (Network Protocol / middleware driver): Pure Java driver that sends JDBC calls to a middleware server using a database-independent protocol, and the middleware communicates with the database. 4. Type-4 (Thin driver / pure Java driver): Pure Java driver that converts JDBC calls directly into the database-specific network protocol; no native library or middleware is needed, so it is the most portable and commonly used type.
-
What is DatabaseMetaData in JDBC? Give examples of the information it provides.
Topic: JDBC & Databases
DatabaseMetaData is an interface of the java.sql package whose object gives comprehensive information about the database as a whole. It is obtained from the connection with con.getMetaData(). Examples of information it provides: database product name (getDatabaseProductName()), database version (getDatabaseProductVersion()), driver name and version (getDriverName(), getDriverVersion()), user name (getUserName()), whether the database is read-only (isReadOnly()), the list of tables (getTables()), and the maximum limits such as maximum number of connections (getMaxConnections()).
-
What is a socket in Java? Differentiate between the Socket and ServerSocket classes.
Topic: Networking, Sockets & Web Basics
A socket is an endpoint of a two-way communication link between two programs running over a network. In Java, socket programming is done with the classes of the java.net package, and communication takes place over TCP/IP using input/output streams. Socket: This class represents the client-side socket. A client creates a Socket object by giving the server's IP address and port number to request a connection, e.g. new Socket("127.0.0.1", 8080). ServerSocket: This class represents the server-side socket. The server creates a ServerSocket on a port and waits for client requests by calling accept(), which blocks until a client connects and then returns a Socket object for communicating with that client.
-
Write down the steps of client/server communication using sockets in Java.
Topic: Networking, Sockets & Web Basics
Server side: 1. Create a ServerSocket on a port, e.g. ServerSocket ss = new ServerSocket(8080); 2. Call Socket s = ss.accept(); and wait — the server blocks until a client connects. 3. Create input/output streams of the returned socket to receive and send data. 4. Communicate with the client (read requests, send responses). 5. Close the streams and the socket when finished. Client side: 1. Create a Socket by providing the server's IP address and port number, e.g. Socket s = new Socket("localhost", 8080); 2. Create input/output streams of the socket. 3. Send requests to the server and read its responses. 4. Close the streams and the socket when finished.
-
What is the URL class in Java? How can data be read from a URL?
Topic: Networking, Sockets & Web Basics
The URL class of the java.net package represents a Uniform Resource Locator — the address of a resource available on the web, e.g. new URL("http://www.vu.edu.pk/index.html"). Its methods such as getProtocol(), getHost(), getPort() and getFile() give the different parts of the address. Data from a URL can be read by opening a stream on it: the openStream() method returns an InputStream connected to the resource, which is normally wrapped in a BufferedReader/InputStreamReader and read line by line, e.g. URL url = new URL("http://www.example.com"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); }