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

IMP Questions With Ans of Java

Constructor is called when an object is instantiated to initialize member variables. It does not have a return type. A method can access object variables, perform operations, and return values. Constructors can call other constructors using this() or parent constructors using super(). Explicit casting is needed when assigning a superclass object to a subclass variable. The garbage collector automatically removes unused objects to free up memory.

Uploaded by

root
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)
58 views

IMP Questions With Ans of Java

Constructor is called when an object is instantiated to initialize member variables. It does not have a return type. A method can access object variables, perform operations, and return values. Constructors can call other constructors using this() or parent constructors using super(). Explicit casting is needed when assigning a superclass object to a subclass variable. The garbage collector automatically removes unused objects to free up memory.

Uploaded by

root
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/ 18

Q 1.

(a) What is the difference between a constructor and a method? ( 5 Marks)

A constructor is a member function of a class that is called when an object of that class is instantiated.

 Contractor name is same as class name


 Its task is to initialize the member variables of class
 Class may have multiple constructors with different set of parameters
 They do not have return types, not even void and therefore they cannot return values.
 They cannot be inherited, A child class can call its parent class constructor.
 It is invoked using the new operator
 They may be public, protected and private

A method is an ordinary member function of a class. It has its own name, a return type (which may be
void), and is invoked using the dot operator. A method can access the internal variables of an object and
can perform some operations on variables.

Multiple methods can be defined with same name and different set of parameters. when multiple methods
have same name then it us called method overloading.

Types of methods:

 Instance Method :- an instance method is associated with an object. It can be called with
object.
o this method can be defined as public String methodName(){..}
 Class Methods :- A class method can access only class variables(attributes). A class
method is defined by a keyword static.
o It syntax is public static void methodName(){}

 Helper Method :- Helper methods are exclusive to a class; only other methods in the
same class can call this type of method.

(b) How do you know if an explicit object casting is needed? ( 5 Marks)

If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting.
For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed
automatically.

(c) Can you call one constructor from another if a class has multiple
constructor? Explain in brief. ( 5 Marks)

Yes, a constructor can call another constructor with the help of this() statement. Since constructors may
receive parameters so when you call a parametrized constructor then you need to pass parameters with
this keyword. Ex. this(DataType1 param1, DataType2 param2, ...);

If you want to call parent class constructor then super keyword will be used.
Constructor call must statement this()/super() must be the first statement in calling constructor. You
can call only one constructor from another constructor.

public class Person {


public Person() {
System.out.println("Person Default Constructor");
}
public Person(String fn, String ln) {
this() ;
firstName = fn;
lastName = ln;
System.out.println("2 param wala const bulaya gaya");
}

public Person(String fn, String ln, String address) {


this(fn,ln) ;
this.address = address;
System.out.println("abhi hum 3 param wale const me he");
}
}

(d) What is the purpose of garbage collection in JAVA and when it is used? (5
Marks)

Garbage Collection is process of discarding orphan objects and releasing primary memory locations
occupied by these objects. An object os called orphan object when its program is finished and it does not
have any use.

Garbage collection is also called automatic memory management as JVM automatically removes the
unused variables/objects (value is null) from the memory.

Garbage collection is done by a daemon thread that is called GARBAGE COLLECTOR. Garbage
collector thread is started by JVM when any JAVA program execution started.

Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage
collector when it determines no more references to the object exists. In Java, it is good idea to explicitly
assign null into a variable when no more in use.

In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects,but there
is no guarantee when all the objects will garbage collected.Garbage collection is an automatic process
and can't be forced. There is no guarantee that Garbage collection will start immediately upon request of
System.gc().

OR

Q 2.

(a) Considering the basic properties of Vector and Array List, where will you use
Array List? Explain. ( 8 Marks)

Vector is synchronous and used in multi-threaded environment when one List is accessed by multiple
threads concurrently.
ArrayList is asynchronous and is used in single threaded environment. By default ArrayList is used.
# ArrayList Vector
1 Not Thread Safe Thread Safe
2 Asynchronous Synchronous
3 No exception is throws if structurally Vector is structurally modified at any time after the
modified in multi-threaded environment Iterator is created, in any way except through the
Iterator's own remove or add methods, the Iterator
will throw a ConcurrentModificationException.

Both implements List interface and permits duplicate elements including null. They have capacity. The
capacity is the size of the array used to store the elements in the list. It is always at least as large as the
list size. As elements are added to a List, its capacity grows automatically.

Ex.

Vector v = new Vector(int initialCapacity);


ArrayList a = new ArrayList(100) ; //Has initial capacity of 100 elements.

(b) Write a program segment that takes as input a sequence of integers from the
user until a number greater than 200 is entered and outputs, how many numbers
were between 0 and 100 and how many numbers were between 100 and 200? (
12 Marks)

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PrintNumber {


public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
int counter100 = 0;
int counter200 = 0;

int num = Integer.parseInt(in.readLine());


while (num <= 200) {
if (num > 0 && num <= 100) {
counter100++;
}
if (num > 100 && num <= 200) {
counter200++;
}
num = Integer.parseInt(in.readLine());
}
System.out.println("Num between 0 to 100 : " + counter100);
System.out.println("Num between 100 to 200 : " + counter200);
}
}

Q 3.

(a) What is the basic difference between the 2 approaches to exception handling
: (i) try catch block (ii) specifying the candidate exceptions in the throws
clause? When should you use which approach? (10 Marks)
try-catch block : It is used to handle an exception within the the method. When an exception is raised in
try block then control goes to its catch block. catch block has exception handling code to handle
abnormal condition.

Example :

public class TestArithmeticException {

public static void main(String[] args) {

int k = 0;
int i = 15;

try {
/** Divide by Zero and raise exception */
double div = i / k;
System.out.println("Div is " + div);

} catch (ArithmeticException e) { // Handle exceptional condition and


print custom message
System.out.println("Divident can not be Zero");
}
}
}

throws clause : It is used when an exception is propagated to its calling method. Many times due to
some coding standards a method does not hands it raised exception and just propagate exception to its
calling method. Called method uses throws clause in its method signature to propagate exception.

Example

public class AccountService {

private static int balance = 100;

public static void main(String[] args) {


try {
fundTransfer(200);
} catch (Exception e) {
System.out.println("Please provide sufficiaent balance");
}

}
public static void fundTransfer(int amount) throws Exception {
if (balance < amount) {
throw new Exception("Insufficient Balance");
}
}

When a method need to have both business operations and its exceptional course of action then try-
catch is used. When a method has business operations and delegate exceptional course of action to
calling method or components then throws clause is used.
(b) What’s the difference an interface and an abstract class? Explain with example. (10
Marks)

An abstract class can have instance methods that implement a default behavior.An Interface can only
declare constants and instance methods, but cannot implement default behavior and all methods are
implicitly abstract. An interface has all public members and no implementation. An abstract class is a
class which may have the usual flavors of class members (private, protected, etc.), but has some abstract
methods.

1. Abstract class is a class which contains one or more abstract methods, which has to be
implemented by sub classes. An abstract class can contain no abstract methods also i.e.
abstract class may contain concrete methods. A Java Interface can contain only method
declarations and public static final constants and doesn't contain their implementation.
The classes which implement the Interface must provide the method definition for all the
methods present.
2. Abstract class definition begins with the keyword "abstract" keyword followed by Class
definition. An Interface definition begins with the keyword "interface".
3. Abstract classes are useful in a situation when some general methods should be
implemented and specialization behavior should be implemented by subclasses.
Interfaces are useful in a situation when all its properties need to be implemented by
subclasses
4. All variables in an Interface are by default - public static final while an abstract class can
have instance variables.
5. An interface is also used in situations when a class needs to extend an other class apart
from the abstract class. In such situations its not possible to have multiple inheritance of
classes. An interface on the other hand can be used when it is required to implement one
or more interfaces. Abstract class does not support Multiple Inheritance whereas an
Interface supports multiple Inheritance.
6. An Interface can only have public members whereas an abstract class can contain private
as well as protected members.
7. A class implementing an interface must implement all of the methods defined in the
interface, while a class extending an abstract class need not implement any of the
methods defined in the abstract class.
8. The problem with an interface is, if you want to add a new feature (method) in its contract,
then you MUST implement those methods in all of the classes which implement that
interface. However, in the case of an abstract class, the method can be simply
implemented in the abstract class and the same can be called by its subclass
9. Interfaces are slow as it requires extra indirection to to find corresponding method in in
the actual class. Abstract classes are fast
10. Interfaces are often used to describe the peripheral abilities of a class, and not its central
identity, E.g. an Automobile class might implement the Recyclable interface, which could
apply to many otherwise totally unrelated objects.

Or

Q 4.

(a) Describe synchronization in respect multithreading. (10 Marks)

With respect to multithreading, synchronization is the capability to control the access of multiple threads
to shared resources. Without synchonization, it is possible for one thread to modify a shared variable
while another thread is in the process of using or updating same shared variable. This usually leads to
significant errors.
With respect to multithreading, Synchronization is a process of controlling the access of shared resources
by the multiple threads in such a manner that only one thread can access a particular resource at a time.
In non synchronized multithreaded application, it is possible for one thread to modify a shared object
while another thread is in the process of using or updating the object's value. Synchronization prevents
such type of data corruption which may otherwise lead to dirty reads and significant errors.
E.g. synchronizing a function:

public synchronized void Method1 () {


// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 (){
synchronized (this) {
// synchronized code here.
}
}

(b) Is it necessary that each try block must be followed by a catch block? (4
Marks)

It is not necessary that each try block must be followed by a catch block. It should be followed by either a
catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the
throws clause of the method.

try {
// ... try block ...
} finally {
// ... finally block ...
}

try {
// ... try block ...
} [catch(error [:ErrorType1]) {
// ... catch block ...
} catch(error[:ErrorTypeN]) {
// ... catch block ...
}] [finally {
// ... finally block ...
}]

Encloses a block of code in which an error can occur, and then respond to the error. If any code in the try
code block throws an error (using the throw statement), control passes to the catch block, if one exists,
and then to the finally code block, if one exists. The finally block is always executed, regardless of
whether an error was thrown. If code in the try block doesn't throw an error (that is, if the try block
completes normally), then the code in the finally block is still executed. The finally block is executed even
if the try block exits using a return statement.

A try block must be followed by a catch block, a finally block, or both. A single try block can have multiple
catch blocks but only one finally block. You can nest try blocks as many levels deep as necessary.

The error parameter specified in a catch handler must be a simple identifier such as e or theException or
x. The variable in a catch handler can also be typed. When used with multiple catch blocks, typed errors
let you catch multiple types of errors thrown from a single try block.
If the exception thrown is an object, the type matches if the thrown object is a subclass of the specified
type. If an error of a specific type is thrown, the catch block that handles the corresponding error is
executed. If an exception that is not of the specified type is thrown, the catch block is not executed and
the exception is automatically thrown out of the try block to a catch handler that matches it.

If an error is thrown within a function, and the function does not include a catch handler, then the
ActionScript interpreter exits that function, as well as any caller functions, until a catch block is found.
During this process, finally handlers are called at all levels.

(c) Differentiate between error and exception. (6 Marks)

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM
errors and you can not repair them at runtime.While exceptions are conditions that occur because of bad
input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a
NullPointerException will take place if you try using a null reference. In most of the cases it is possible to
recover from an exception (probably by giving user a feedback for entering proper values etc.).

1. An Exception can be caught and recovered: ArrayIndexOutOfBoundsException means


you tried to access a position of an Array that does not exist - no big deal.An Error is
unrecoverable: OutOfMemoryError means that the JVM has no more memory to contin
2. Exceptions are those which can be handled at the run time where as errors cannot be
handled.Examples for exceptions: Array out of bonds, attempt todivide by zero etc
3. Exceptions can be handled by handlers using try - catch.The functional diiference, in
terms of the compiler, is that you don't have to declare errors in throws clauses on
methods, or catch them.Conceptually, an Error means something has gone wrong with
your program, which should usually give up and crash, whereas an exception is for an
unusual situation that you, as a programmer, anticipated as a possibilty. So, for example,
a divide-by-zero is an Error, but attempting to read a file and finding it doesn't exist is an
Exception

Q 5.

(a) What is Applet framework ? ( 5 Marks)

The Windows Control Panel is the ideal way to allow a user to alter settings for an application that runs in
the background, or automatically. But what are control panel applets and how do you write one? Well,
after some exploring in the MSDN I discovered that control panel applets are just standard DLLs with a
particular set of entry points and a .cpl extension. Place such a file in the Windows System directory and
the next time you start up control panel your applet will be there. Having discovered what I needed to
know I set about writing a control panel applet and once I'd done that, I turned the bulk of the code into a
mini applet framework so I wouldn't have to write it ever again!To implement your control panel applet all
you need to do is the following:

 include "ControlApplet.hpp" and publicly derive a class from CJBControlPanelApplet.

 call the CJBControlPanelApplet constructor and pass resource IDs for the applet's icon,
name an description.
 implement the pure virtual function OnDoubleClick() - this is where your applet becomes
live and can display a dialog or whatever.

 create an instance of your applet class at global scope.

 link with ControlApplet.cpp and include ControlApplet.def in your


project.ControlApplet.cpp gives you the implementation of CJBControlPanelApplet and
suitable DllMain() and CPlApplet() DLL entry point functions.

(b) Can we pass parameters to an applet from HTML page to an applet.How?


(5 Marks)

Then in the function paint (Graphics g), we prints the parameter value to test the value passed from html
page. Applet will display "Hello! Java Applet" if no parameter is passed to the applet else it will display the
value passed as parameter. In our case applet should display "Welcome in Passing parameter in java
applet example." message.

Here is the code for the Java Program :

import java.applet.*;
import java.awt.*;

public class appletParameter extends Applet {


private String strDefault = "Hello! Java Applet.";
public void paint(Graphics g) {
String strParameter = this.getParameter("Message");
if (strParameter == null)
strParameter = strDefault;
g.drawString(strParameter, 50, 25);
}
}

Here is the code for the html program :

<HTML>
<HEAD>
<TITLE>Passing Parameter in Java Applet</TITLE>
</HEAD>
<BODY>
This is the applet:<P>
<APPLET code="appletParameter.class" width="800" height="100">
<PARAM name="message" value="Welcome in Passing parameter in java applet example.">
</APPLET>
</BODY>
</HTML>

There is the advantage that if need to change the output then you will have to change only the value of
the param tag in html file not in java code.

(c) What are the Applet’s information methods? (5 Marks)


A method is a program structure consisting of variables and statements that can receive parameters and
may return one value. A method may have local variables and it may use member variables. Method
parameters are defined, with their data type, in the method argument list. Methods must have a return
type. If no data is returned from a method it must be specified as "void". In the Contact applet the
handleEvent() and action() methods are both boolean methods. All the other methods in the Contact
applet are void. Methods have numerous access specifiers and modifiers that are well documented.

The browser controls the applet's behavior by executing four standard applet methods named: init(),
start(), stop(), and destroy(). An applet requires the initialization code to be placed in the init() method,
which is the first method called by the browser to get things going. An applet may optionally override the
other three methods in order to perform functions at certain times in the lifecycle of the applet as listed in
the table below.

Method Executed by browser when an HTML document that contains the applet:
Name

Init() Is loaded by the browser

Start() Is displayed by the browser or revisited and displayed

Stop() Is closed by browser or the browser is shut down.

Destroy() After stop

In the Contact applet we have included a System.out.println() statement in these methods. This print
statement illustrates the sequence of events as initiated by the browser. The output from these print
statements is written into the Java console. The Java console is just a file on your computer. Its name
and directory depends on the operating system and browser you are using. If you are using Windows 95
and Netscape Navigator the Java console is available under the Options menu and accessed under the
option Show Java Console. If your using Windows 95 and Microsoft Internet Explorer the Java console is
located in a file called javalog.txt which may be in the \Windows\Java\ directory. Under Microsoft Internet
Explorer to see the javalog.txt file you have to shut down your browser first then use a text editor to look
at the file. You may need to consult your browser help screens to locate the Java console on your specific
operating system.

(d) How do Applets differ from Applications? (5 Marks)

# Application Applet
1 An application runs stand-alone, An applet runs under the control of a browser.
with the support of a virtual
machine.
2 The true power of Java lies in Applets are great for creating dynamic and interactive web
writing full blown applications. applications
3 In an application execution starts Applets don't have the main method.
with the main method.
4 The applications run on Desktop. Applets are designed for the client site programming purpose,
downloaded and run on Browser.
5 The java applications are Applets are designed just for handling the client site problems.
designed to work with the client
as well as server.
6 Applications are designed to exist The applets can run in secure and unsecured environment
in a secure area.
7 Does not require to inherit any Applet need to inherit java.awt.Applet class
class
8 Static block is called at time of init() method is called at time of applet creation and destroy()
application call method is called at time of applet destruction
9 Does not have any other life Has init(), start(), paint(), stop(), destroy() life cycle methods
cycle methods

Applet:-

import java.awt.*;
import java.applet.*;

class ClassName extends Applet {

public void init() {


System.out.println("This is init method"); //called only once
}

public void start() {


System.out.println("This is Start method"); //Called again and again when applet is activated (browser
window is maximized)
}

public void stop() {


System.out.println("This is Start method"); //Called again and again when applet is deactivated
(browser window is minimized)
}

public void paint(Graphics g) {


System.out.println("This is Paint method"); //Called again and again when applet is rendered
}

Application:-

public class ClassName {


public static void main(String args[]) {
System.out.println("Hello Application");
}
}

OR

Q 6.

(a) What are the types of Checkboxes in JAVA and what is the difference
between them? ( 6 Marks)

Java supports two types of Checkboxes:-


• Exclusive
• Non-exclusive.
In case of exclusive Checkboxes, only one among a group of items can be selected at a time.
if an item from the group is selected, the checkbox currently checked is deselected and
the new selection is highlighted.
The exclusive Checkboxes are also called as Radio buttons. The non-exclusive checkboxes
are not grouped together and each one can be selected independent of the other.

(b) Which method of the component class is used to set the position and the
size of a component? Explain with example. ( 6 Marks)

first of all set the Layout to null then apply setBounds();


setLayout(null);
Component.setLayout(x y width height);

(c) What are the subclasses of the container class? Discuss in brief. ( 6 Marks)

Subclasses of Container in java.awt


class Dialog
A Dialog is a top-level window with a title and a border that is typically used to take some
form of input from the user.
class FileDialog
The FileDialog class displays a dialog window from which the user can select a file.
class Frame
A Frame is a top-level window with a title and a border.
class Panel
Panel is the simplest container class.
class ScrollPane
A container class which implements automatic horizontal and/or vertical scrolling for a
single child component.
class Window
A Window object is a top-level window with no borders and no menubar.
(d) What is the highest level event class of the event-delegation Model? ( 2
Marks)

Event types are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is propagated
from a "Source" object to a "Listener" object by invoking a method on the listener and passing in the
instance of the event subclass which defines the event type generated.
A Listener is an object that implements a specific EventListener interface extended from the generic
java.util.EventListener. An EventListener interface defines one or more methods which are to be invoked
by the event source in response to each specific event type handled by the interface.
An Event Source is an object which originates or "fires" events. The source defines the set of events it
emits by providing a set of set<EventType>Listener (for single-cast) and/or add<EventType>Listener (for
mult-cast) methods which are used to register specific listeners for those events.
In an AWT program, the event source is typically a GUI component and the listener is commonly an
"adapter" object which implements the appropriate listener (or set of listeners) in order for an application
to control the flow/handling of events. The listener object could also be another AWT component which
implements one or more listener interfaces for the purpose of hooking GUI objects up to each other.

Event Listeners

An EventListener interface will typically have a separate method for each distinct event type the event
class represents. So in essence, particular event semantics are defined by the combination of an Event
class paired with a particular method in an EventListener. For example, the FocusListener interface
defines two methods, focusGained() and focusLost(), one for each event type that FocusEvent class
represents.
The API attempts to define a balance between providing a reasonable granularity of Listener interface
types and not providing a separate interface for every single event type.
The low-level listener interfaces defined by the AWT are as follows:
java.util.EventListener
java.awt.event.ComponentListener
java.awt.event.ContainerListener
java.awt.event.FocusListener
java.awt.event.KeyListener
java.awt.event.MouseListener
java.awt.event.MouseMotionListener
java.awt.event.WindowListener
The semantic listener interfaces defined by the AWT are as follows:
java.util.EventListener
java.awt.event.ActionListener
java.awt.event.AdjustmentListener
java.awt.event.ItemListener
java.awt.event.TextListener

Q 7.

(a) What is the role of following type of JDBC statements? (i)


JAVA.sql.statement, (ii) JAVA.sql.preparedstatement, (iii)
JAVA.sql.callable.statement. (10 Marks)

(i) java.sql.Statement- A Statement object is used for executing a static SQL statement and obtaining
the results produced by it. Only one ResultSet per Statement can be open at any point in time. Therefore,
if two ResultSet are required then two statements need to be created All statement execute method
implicitly close all its opened ResultSets.

Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root",
"root");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT id, name, color from part");

(ii) java.sql.PreparedStatement- An object that represents a precompiled SQL statement. A SQL


statement is precompiled and stored in a PreparedStatement object. This object can then be used to
efficiently execute this statement multiple times. Note: The setter methods (setShort, setString, and so on)
for setting IN parameter values must specify types that are compatible with the defined SQL type of the
input parameter. For instance, if the IN parameter has SQL type INTEGER, then the method setInt should
be used. If arbitrary parameter type conversions are required, the method setObject should be used with
a target SQL type.

In the following example of setting a parameter, con represents an active connection:

PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES SET SALARY =


? WHERE = ?");
pstmt.setBigDecimal(1, 153833.00);
pstmt.setInt(2, 110592);
pstmt.executeUpdate();

(iii) JAVA.sql.CallableStatement -CallableStatement extends PreparedStatement. CallableStatement is


used to execute SQL Stored Procedures or Stored Function. JDBC provides a stored procedure SQL
escape that allows stored procedures to be called in a standard way for all RDBMS's. This escape syntax
has one form that includes a result parameter and one that does not. If used, the result parameter must
be registered as an OUT parameter. The other parameters may be used for input, output or both.
Parameters are refered to sequentially, by number. The first parameter is 1.

{?= call <procedure-name>[<arg1>,<arg2>, ...]}


{call <procedure-name>[<arg1>,<arg2>, ...]}

IN parameter values are set using the set methods inherited from PreparedStatement. The type of all
OUT parameters must be registered prior to executing the stored procedure; their values are retrieved
after execution via the get methods provided here.

A Callable statement may return a ResultSet or multiple ResultSets. Multiple ResultSets are handled
using operations inherited from Statement.For maximum portability, a call's ResultSets and update counts
should be processed prior to getting the values of output parameters.

Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");

CallableStatement callStmt = conn.prepareCall("{CALL ProTest(?)}");

callStmt.registerOutParameter(1, Types.INTEGER);

callStmt.execute();

(b) Explain the following: (i) DriverManager class, (ii) SQLPermission


class, (iii) Driver interface. (10 Marks)
(i) Driver Manager class:- The Driver Manager class is the traditional management layer of JDBC,
working between the user and the drivers. It keeps track of the drivers that are available and handles
establishing a connection between a database and the appropriate driver. In addition, the DriverManager
class attends to things like driver login time limits and the printing of log and tracing messages.The only
method in the DriverManager class that a general programmer needs to use directly is
DriverManager.getConnection(URL, LOGIN, PASSWORD);. As its name implies, this method establishes
a connection to a database.

(ii) SQL Permission class:- A SQLPermission object contains a name (also referred to as a target name)
but no actions list, there is either a named permission or there is not. The target name is the name of the
permission. The naming convention follows the hierarchical property naming convention.SQLPermission
class extends BasicPermission class in which permission for the SecurityManager will check when code
that is running in an applet calls the DriverManager.setLogWriter method or the
DriverManager.setLogStream (deprecated) method. If there is no SQLPermission object, these methods
throw a java.lang.SecurityException as a runtime exception.

(iii) Driver interface:- Driver interface is a Java SQL framework which allows for multiple database
drivers. It is a interface that every driver class must implement. Each driver should supply a class that
implements the Driver interface. The DriverManager will try to load as many drivers as it can find and then
for any given connection request, it will ask each driver in turn to try to connect to the target URL.it is
strongly recommended that each Driver class should be small and standalone so that the Driver class can
be loaded and queried without bringing in vast quantities of supporting code.When a Driver class is
loaded, it should create an instance of itself and register it with the DriverManager. This means that a
user can load and register a driver by calling Class.forName("com.mysql.jdbc.Driver").

Q 8.

(a) What are the types of JDBC Driver Models and explain them. (10 Marks)

The different types of jdbc drivers are:


Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

Type 1 - drivers that implement the JDBC API as a mapping to another data access API, such as ODBC.
Drivers of this type are generally dependent on a native library, which limits their portability. The
JDBC-ODBC Bridge driver is an example of a Type 1 driver.

Type 2 - drivers that are written partly in the Java programming language and partly in native code. These
drivers use a native client library specific to the data source to which they connect. Again, because of
the native code, their portability is limited.

Type 3 - drivers that use a pure Java client and communicate with a middleware server using a database-
independent protocol. The middleware server then communicates the client?s requests to the
data source.

Type 4 - drivers that are pure Java and implement the network protocol for a specific data source. The
client connects directly to the data source.

.
(b) What is the difference between Reader/Writer and
InputSteam/OutputStream? Explain with example. (10 Marks)

1. The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-


oriented.
2. Reader/writer belongs to the charecter stream I/P and O/P belongs to the byte stream.
3. reader/writer support only cahracter and input/output stream support only bytes input stram and the
java reader
class has only one differnce and that is input stream only support bytes and the reader class only
supports the character.
Or

Q 10.

(a) What is collection interface? How can we use hashset in collection


interface? (10 Marks)

Collection interface: - A collection represents a group of objects, known as its elements. Some
collections allow duplicate elements and others do not. Some are ordered and others unordered. It has
Set, List and Queue child interfaces. This interface is typically used to pass collections around and
manipulate them where maximum generality is desired.

All general-purpose Collection implementation classes (which typically implement Collection indirectly
through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments)
constructor, which creates an empty collection, and a constructor with a single argument of type
Collection, which creates a new collection with the same elements as its argument. In effect, the latter
constructor allows the user to copy any collection, producing an equivalent collection of the desired
implementation type.

Some collection implementations have restrictions on the elements that they may contain. For example,
some implementations prohibit null elements, and some have restrictions on the types of their elements.
Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or
ClassCastException.

public class TestHashSet {

public static void main(String[] args) {

HashSet hSet = new HashSet();

// You can insert any object in the HashSet. Here it is string

hSet.add("Jay");
hSet.add("Viru");
hSet.add("Basanti");

System.out.println("Some Importent Methods");


System.out.println(" Set size : " + hSet.size());
System.out.println(" Contains Jay : " + hSet.contains("Jay"));

/*
* Primitive data type need to be converted into Objects before
* inserting. Get all elements and print with help of Iterator
interface
*/
Iterator it = hSet.iterator(); // Get an iterator

System.out.println("\nPrint All Elements with help of Iterator ");

while (it.hasNext()) { // Checks if any element in list


Object oo = it.next(); // Get next available element
System.out.println(" From Iterator -- " + oo);
}

// Clear all elements


hSet.clear();
System.out.println(" Is Empty " + hSet.isEmpty());

}
}

(b) Write notes on the following? ( 5 each Marks)

Collection Classes :-

A collection represents a group of objects, known as its elements. Some collections allow duplicate
elements and others do not. Some are ordered and others unordered. The SDK does not provide any
direct implementations of this interface: it provides implementations of more specific subinterfaces like
Set and List. This interface is typically used to pass collections around and manipulate them where
maximum generality is desired.

Key Classes and Interfaces

Interface Set List Map

Implementation HashSet HashMap


ArrayList
TreeSet Treemap
LinkedList
Historical Vector Stack Hashtable Properties

ArrayList - A dynamic duplicate element list.


Vector - A dynamic duplicate element list. It is thread safe.
HashSet - A dynamic unique element set
TreeSet - A dynamic unique element sorted set.
HashMap - A dynamic index map.
Hashtable - A dynamic index map. It is thread safe.
Iterator - Access elements sequentially from a SET and LIST
Enumeration - Access elements sequentially from a Vector and Hashtable

All general-purpose Collection implementation classes should provide two "standard" constructors: a void
(no arguments) constructor, which creates an empty collection, and a constructor with a single argument
of type Collection, which creates a new collection with the same elements as its argument. In effect, the
latter constructor allows the user to copy any collection, producing an equivalent collection of the desired
implementation type.
Some collection implementations have restrictions on the elements that they may contain. For example,
some implementations prohibit null elements, and some have restrictions on the types of their elements.
Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or
ClassCastException. Attempting to query the presence of an ineligible element may throw an exception,
or it may simply return false; some implementations will exhibit the former behavior and some will exhibit
the latter. More generally, attempting an operation on an ineligible element whose completion would not
result in the insertion of an ineligible element into the collection may throw an exception or it may
succeed, at the option of the implementation. Such exceptions are marked as "optional" in the
specification for this interface.

You might also like