0% found this document useful (0 votes)
209 views14 pages

Current Midterm Solved Papers: Muhammad Faisal Dar

The document contains solutions to multiple questions asked in a midterm exam. The first question asks for the 8 steps of connecting to a database using JDBC. The solution lists the 8 steps which include importing packages, loading drivers, defining connection URLs, establishing connections, creating statements, executing queries, processing results, and closing connections. The second question asks to write code that handles window events in Java to display "welcome" when opened and "good bye" when closed. The solution provides a complete code example using the WindowListener interface that implements these requirements. The third question asks to write server code for a given port number. The solution provides a code example of a server that listens on port 2222

Uploaded by

Ali Bhatti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
209 views14 pages

Current Midterm Solved Papers: Muhammad Faisal Dar

The document contains solutions to multiple questions asked in a midterm exam. The first question asks for the 8 steps of connecting to a database using JDBC. The solution lists the 8 steps which include importing packages, loading drivers, defining connection URLs, establishing connections, creating statements, executing queries, processing results, and closing connections. The second question asks to write code that handles window events in Java to display "welcome" when opened and "good bye" when closed. The solution provides a complete code example using the WindowListener interface that implements these requirements. The third question asks to write server code for a given port number. The solution provides a code example of a server that listens on port 2222

Uploaded by

Ali Bhatti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Current Midterm Solved Papers

By
Muhammad Faisal Dar
[email protected]

8 steps of jdbc connect with database? 3marks


Solution:
1. Import Required Package as “import java.sql.*;”
2. Load Driver as “Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);”
3. Define Connection URL as “String conURL = “jdbc:odbc:personDSN”;”
4. Establish Connection with Database as “Connection con =
null;con = DriverManager.getConnection(conURL, usr, pwd);”
5. Create Statement as “Statement stmt = con.createStatement( ); ”
6. Execute a Query
String sql = “SELECT * from sometable”;
ResultSet rs = stmt.executeQuery(sql);
7. Process Results of the Query
8. Close the Connection
con.close();

1 program tha jis may hum nay event handler or registration ka code likhna tha jo k
open karnay say" welceom" or close karnay say "good by" appear karay.5marks
Solution:

To handle window events, we need to implement “WindowListner” interface.


“WindowListner” interface contains 7 methods we require only one i.e. windowClosing
But, we have to provide definitions of all methods to make our class a concrete class

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class EventsEx implements WindowListener
{
JFrame frame;
public EventsEx ( )
{
initGUI();
}
public void initGUI ( )
{
frame = new JFrame();
frame.setLayout(new BorderLayout( ) );
frame.setSize(350, 350);
frame.setVisible(true);
//Registering a window Event Handler
frame.addWindowListener(this);
}
public void windowOpened (WindowEvent we)
{
JOptionPane.showMessageDialog(null,"Wel Come");
}
public void windowClosing (WindowEvent we)
{
JOptionPane.showMessageDialog(null,"Good
Bye"); System.exit(1);
}
Public void windowActivated (WindowEvent we) { }
public void windowClosed (WindowEvent we) { }
Public void windowDeactivated (WindowEvent we) { }
public void windowDeiconified (WindowEvent we) { }
public void windowIconified (WindowEvent we) { }

public static void main(String args[])


{
EventsEx ex = new EventsEx();
}
}
server ka code likhna tha.port number given tha .5 marks

Solution: import
java.net.*;
import java.io.*;
import javax.swing.*;

public class EchoServer


{
public static void main(String args[])
{
try
{
//step 2: create a server socket ServerSocket
ss = new ServerSocket(2222);
System.out.println("Server started...");
/* Loop back to the accept method of the serversocket and wait for a
new connection request. So, server will continuously listen for requests
*/
while(true)
{
// step 3: wait for incoming
connection Socket s = ss.accept();
System.out.println("connection request recieved");
// step 4: Get I/O streams
InputStream is = s.getInputStream();
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os,true);
// step 5: Send / Receive message

// reading name sent by client


String name = br.readLine();
// appending “hello” with the received name
String msg = "Hello " + name + " from Server";
// sending back to client
pw.println(msg);
// closing communication
socket s.close();
} // end while
}
catch(Exception ex)
{
System.out.println(ex);
}
}
} // end class

How UDP are different instead of TCP.


Solution:
There are different protocols available to communicate such as TCP and UDP. We will use
TCP for programming in this handout. There are 64k ports available for TCP sockets and 64k
ports available for UDP, so at least theoretically we can open 128k simultaneous connections.
The major difference between both is that UDP is a connectionless and TCP is
connection oriented.

Given columncount() and given columnlabel().2marks


Solution:
columncount() method return the total number of column/fields of the
current given ResultSet. columnLabel() method is use for setting or getting the
Display name or Allias of columns.

Update execute ka code likhna tha.2marks


Solution:
Use to execute for INSERT, DELETE AND UPDATE statement. This method returns the
number of rows that were affected in the database. Also supports DDL (Data Definition
Language) statements CREATE TABLE, DROP TABLE, ALTER TABLE etc.
int num = stmt.executeUpdate(“DELETE from Person WHERE id = 2” );
MCQs CS506 fall 2012

3. Converting bigger dataset into small (Down


Casting) or
Converting small dataset into bigger (Up Casting)
(Options: Down Cast, Up Cast, In Cast and Out Cast)

6. Name of top level container?


Solution:
General purpose containers cannot exist alone they must be added to top level containers
Examples of top level container are JFrame, Dialog and Applet etc. Our application uses one
of these. Examples of general purpose container are JPanel, Toolbar and ScrollPane etc.

7. transient keyword is prevent serialization (Options: allow, prevent, avoid, none of above)

Subjective Questions
1. Why Applet is a panel? (2 number)
Solution:
An applet is a Panel that allows interaction with a Java program. Because it is
inherited from the container class, so the applet are also the panel.

2. Java database connectivity ? (2


number) a. why we need drivers
Solution:
To get the access to the database we use drivers specific to the DBMS. These
drivers are interface to manage the Database from the your application. Without driver it is hard to
handle that DBMS. For communication with DBMS we need a driver specific to the DBMS.

b. odbc and jdbc


Solution:
ODBC stands for Open Database Connectivity. It is a standard way for
communication to any DBMS that support ODBC driver, provided by the Microsoft.
JDBC stands for Java Database Connectivity. It is a standard way for
communication to any DBMS that support JDBC driver, provided by the Sun Java.

2. Client Server Connection, write code? (5


number) Solution:
Server Code:
import java.net.*;
import java.io.*;
import javax.swing.*;

public class EchoServer


{
public static void main(String args[])
{
try
{
//step 2: create a server socket ServerSocket
ss = new ServerSocket(2222);
System.out.println("Server started...");
/* Loop back to the accept method of the serversocket and wait for a
new connection request. So, server will continuously listen for requests
*/
while(true)
{
// step 3: wait for incoming
connection Socket s = ss.accept();
System.out.println("connection request recieved");
// step 4: Get I/O streams
InputStream is = s.getInputStream();
InputStreamReader isr= new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os,true);
// step 5: Send / Receive message

// reading name sent by client


String name = br.readLine();
// appending “hello” with the received name
String msg = "Hello " + name + " from Server";
// sending back to client
pw.println(msg);
// closing communication
socket s.close();
} // end while
}
catch(Exception ex)
{
System.out.println(ex);
}
}
} // end class
Client Code:

// step 1: importing required


package import java.net.*;
import java.io.*;
import javax.swing.*;

public class EchoClient


{
public static void main(String args[])
{
try {
//step 2: create a communication socket
// if your server will run on the same machine
thenyou can //pass “localhost” as server address

/* Notice that port no is similar to one passedwhile creating


server socket server */ Socket s = new Socket(“localhost”, 2222);
// step 3: Get I/O streams
InputStream is = s.getInputStream();
InputStreamReader isr= new
InputStreamReader(is);
BufferedReader br = new
BufferedReader(isr); OutputStream os =
s.getOutputStream(); PrintWriter pw = new
PrintWriter(os,true);
// step 4: Send / Receive message
// asking use to enter his/her name
String msg = JOptionPane.showInputDialog("Enter your name");
// sending name to
server pw.println(msg);
// reading message (name appended with hello) from//
servermsg = br.readLine();
// displaying received message
JOptionPane.showMessageDialog(null , msg);
// closing communication
sockets.close();
}
catch(Exception ex)
{
System.out.println(ex);
}
}// end main
}
// end class

4. Importance of DDL statement in SQL? (5 number)


Solution:
DDL stands for Data Definition Language. It play a important role in creating a
Database, Tables, Views, and Altering the structure of these object. In the DDL the
following command are used, CREATE TABLE, CREATE DATABASE, ALTER TABLE etc.

What will happen if we call these two statements in the following


order? i)Rs.moveToInsertRow();
ii)Rs.deleteRow();
Solution:
New Blank Row will be appened at the end of the ResultSet and by executing the
second one that row will be removed.

Name component subclasses that support painting?


Solution:
Container, JComponent, Windows, Frame, JFrame, JPanel, AbstractButton, JButton

Write SQL Query in Java to create a Result Set n columns using columns “employee
Name” and “employee id” from table “Employee”.
Solution:
String varsql=”SELECT [employee Name], [employee id] FROM
Employee”; PreparedStatement pStmt = con.prepateStatement(sql);
ResultSet rs= pStmt.executeQuery(varsql);

What is function of paintcomponent method?


Solution:
Window is like a painter’s canvas. All window paints on the same surface.
More importantly, windows don’t remember what is under them. There is a need to
repaint when portions are newly exposed. Java components are also able to paint
themselves. Most of time, painting is done automatically. However sometimes you
need to do drawing by yourself. Anything else is programmer responsibility

Paintcomponent() method
— it is a main method for painting
— By default, it first paints the background
— After that, it performs custom painting (drawing circle, rectangles etc.)

Write the names of any five event listener interfaces which are sub
interfaces of Java util.EventListner interface?
Solution:
1. ActionListener
2. AdjustmentListener
3. ComponentListener
4. ContainerListener
5. FocusListener
6. ItemListener
7. KeyListener
8. MouseListener
9. MouseMotionListener
10. TextListener
11. WindowListener

If we use serialization in our Java Program what we don’t need to merge as


serialization feature will automatically manage for us?
Solution:
If we use serialization in our Java Program what we don’t need to merge the manual
parsing of the data member of class, as serialization feature will automatically manage for us.

What is the concept of Inheritance in Java ? (3)


Solution:
In java parent or base class is referred as super class while child or derived class is
known as sub class.
1. Java only supports single inheritance. As a result a class can only inherit from
one class at one time.
2. Keyword extends is used instead of “:” for inheritance.
3. All functions are virtual by default
4. All java classes inherit from Object class (more on it later).
5. To explicitly call the super class constructor, use super keyword. It’s
important to remember that call to super class constructor must be first line.
6. Keyword super is also used to call overridden methods.

What are methods of Mouse Events ? describe few ?(Mouse Listener Interface
methods to handel mouse events)
Solution:
To handle Mouse events, two types of listener interfaces are available.

– MouseMotionListener
– MouseListener

The class that wants to handle mouse event needs to implement the corresponding
interface and needs to provide the definition of all the methods in that interface.

MouseMotionListener interface
– Used for processing mouse motion events
– Mouse motion event is generated when mouse is moved or dragged

public interface MouseMotionListener


{

public void mouseDragged (MouseEvent me){}


public void mouseMoved (MouseEvent me){}
}

MouseListener interface
– Used for processing “interesting” mouse events like when m
ƒ Pressed
ƒ Released
ƒ Clicked (pressed & released without moving the cursor)
ƒ Enter (mouse cursor enters the bounds of component)
ƒ Exit (mouse cursor leaves the bounds of component)

public interface MouseListener


{

public void mousePressed (MouseEvent me){}


public void mouseClicked (MouseEvent me){}
public void mouseReleased (MouseEvent me){}
public void mouseEntered (MouseEvent me){}
public void mouseExited (MouseEvent me){}

What are the types of errors encoutered in Java ?


Solution
1. Syntax Errors
Arise because the rules of the language are not followed.
2. Logic Errors
Indicates that logic used for coding doesn’t produce expected output.
3. Runtime Errors
Occur because the program tries to perform an operation that is impossible to
complete. Cause exceptions and may be handled at runtime (while you are
running the program) For example divide by zero

Why server communicats with one client at a time using socket ?


Solution:
Because when we program the server and client program we give the fix socket
no which is a one. On a single port only one communication channel is possible. So
that server communicates with one client at a time using a socket.

Difference b/w Checked and Unchecked Exceptions


Solution:
Exceptions can be broadly categorized into two types, Unchecked & Checked Exceptions.
Unchecked Exceptions
• Subclasses of RuntimeException and Error.
• Does not require explicit handling
• Run-time errors are internal to your program, so you can get rid of
them by debugging your code
• For example, null pointer exception; index out of bounds exception; division
by zero exception
Checked Exceptions
• Must be caught or declared in a try catch or throws clause
• Compile will issue an error if not handled appropriately
• Subclasses of Exception other than subclasses of RuntimeException.
• Other arrive from external factors, and cannot be solved by debugging
• Communication from an external resource – e.g. a file server or
database Question No 1 MARKS 2
Write a given connection URL in string variable conURL. How will you connect to MS
Access database using conURL in your java program?
Solution:
String conURL = “jdbc:odbc:personDSN”;
Connection con = null;
con = DriverManager.getConnection(conURL);
Shortcut Method
Connection con= DriverManager.getConnection("jdbc:odbc:personDSN");
Question No 2 MARKS 2
Complete syntax of paint Border method
Solution:
protected void
paintBorder(Graphics g) {}
) to paint.
paintBorder( ) tells the components border (if any) to paint.It is suggested that
you do not override or invoke this method

Question No 3 MARKS 3
Write java code that will update name Ali to Ahmed on 5th row. Consider the column
name is sname note write only necessary code
Solution:
Rs.absolute(5)

Question No 4 MARKS 3
Methods (paintBorder, paintChildren, paintComponent) write correct order of methods
call in if these methods are called
Solution:
1. paintComponent
2. paintBorder
3. paintChildren

First of all JComponent paint itself, painting the background and performing custom
painting is performed by the paintComponent method. Then paintBorder is get called
And finally Childern is called. All these methods are also called in the same order.

1.Difference B/w Writer/Reader Class Hierarchy and Input/output Stream 2


marks Solution:
Java programs perform file processing by using classed from package
java.io. This package include definition for stream classes, such as
FileInputStream (For byte-based input form a file)
FileOutputStream (for byte-based output to a file)
FileReader (for character-base input form a file)
FileWriter (for character-based output to a file)

Which inherit from classes InputStream, OutputStream, Reader and Writer,


respectively. So, the Writer/Reader class hierarchy is used or character-based file
access while the Input/Output Stream is used for byte-based file access.
2.write Next() Method which is used in ResultSet 2 marks
Solution:
ResultSet rs;
if (rs.Next())
{
rs.getString(0);
}
6. give a code which display result is Hello World 3 marks
Solution:
public class HelloWorld
{
public static void main (String[] args)
{
JOptionPane.showMessageDialog(null,”Hello World”);
}
}

Each event source can have _________________ listeners


registered on it. Multiple
Single
Double
Triple

Which of the following methods are invoked by the AWT to support paint and
repaint operations?
Paint ()
Repaint()
Draw ()
Redraw()
Java gives us a solution in the from of repaint( ) method. Whenever we need to repaint,
we call this method that in fact makes a call to paint( ) method at appropriate time.

An exception in java is represented as a/an _____


Operator
Object
Function
None
In java expect the some basic primitive data type as integer, long, double etc,
every thing is object. So the exception is also an object.

Window, frame and dialog use ________ as their default layout.


Border Layout
Flow Layout
Grid Layout
Gridbag Layout

Adapter classes have been defined for listener interfaces except ________
interface 1. MouseListener
2. KeyListener
3. WindowListener
4. ActionListener

What is the difference between a static and a non-static inner class?


Solution:
A non-static inner class may have object instances that are associated with instances
of the class’s outer class. A static inner class does not have any object instances

Discuss any three methods of ResultSetMetaData?


Solution:
getColumnCount ( )
Returns the number of columns in the
result set getColumnDisplaySixe(int)
Returns the maximum width of the specified column in
characters getColumnName(int)/getColumnLabel(int)
The get ColumnName() method returns the database name of the column.
The get ColumnLabel() method returns the suggested column label for
printouts. getColumnType(int)
Returns the SQL type for the column to compare against types in java.sql.Types

Two java collections.Which Should use for Your indexed Search?


Solution:
1. ArrayList
2. HashMap
For our indexed search HashMap collection is the best to use.

Which Component subclasses are used for


paint 4 stages of applet cycles
Solution:
The applet’s life cycle methods are called in the specific order shown below. Not
every applet needs to override every one of these methods.
> What will happen if a class implements Windowlistener Interface and it does not
provide definitions of all methods.?
Solution:
If a class implements WindowListener Interface and it does not provide
definitions of all methods. The program will be compile and procude the error.

Methods to execute SQL query?


Solution:
Create the sql statement and then run the executeQuery
method. rs=stmt.executeQuery(“Select * from student”);

> What does mean by it if a class or method is abstract? (5 marks)


Solution:
An abstract class or method is a method that has no implementation. Abstract classed are used
to define only part of an implementation. Because, information is not complete therefore an
abstract class cannot be instantiate. The class that inherits from abstract class is responsible to
provide details. If subclass overrides all abstract methods of the super class, then it become a
concrete (a class whose object can be instantiate) class otherwise we have to declare it as
abstract or we can not compile it. The most important aspect of abstract class is that reference
of an abstract class can point to the object of concrete classes.

> Diff b/w Input/output streams class hierarchy and Read/Write class hierarchy?
> Can applets communicate with eachother? (5 marks)
Solution:

> As a developer of GUI, what should u know about top level containers and general
purpose containers?
Solution:
As a developer of GUI, a developer should know about top level containers and general
purpose containers that a top general purpose container cannot be visible at runtime
without top level containers. Only top levels container have a capability of displaying alone.
What is the difference between a static and a non-static inner class?
Solution:
A non-static inner class may have object instances that are associated with instances
of the class’s outer class. A static inner class does not have any object instances

What is the difference between Anonymous object and Named object? Give example with code.
Solution:
Has no name, Same as inner class in capabilities, much shorter and
difficult to understand.
Nave VS Anonymous Objects

Named
String s=”hello”;
System.out.println(s);
“Hello” had a named reference s.
Anonymous
System.out.println(“hello”);

We generally use anonymous object when there is just a one time use of a particular
object but in case of a repeated use we generally used named objects and use that
named reference to use that objects again and again.

You might also like