IMP Questions With Ans of Java
IMP Questions With Ans of Java
A constructor is a member function of a class that is called when an object of that class is instantiated.
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.
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.
(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.
(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;
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 :
int k = 0;
int i = 15;
try {
/** Divide by Zero and raise exception */
double div = i / k;
System.out.println("Div is " + div);
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 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.
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:
(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.
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.).
Q 5.
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:
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.
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.
import java.applet.*;
import java.awt.*;
<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.
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
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.
# 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.*;
Application:-
OR
Q 6.
(a) What are the types of Checkboxes in JAVA and what is the difference
between them? ( 6 Marks)
(b) Which method of the component class is used to set the position and the
size of a component? Explain with example. ( 6 Marks)
(c) What are the subclasses of the container class? Discuss in brief. ( 6 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.
(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");
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");
callStmt.registerOutParameter(1, Types.INTEGER);
callStmt.execute();
(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)
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)
Q 10.
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.
hSet.add("Jay");
hSet.add("Viru");
hSet.add("Basanti");
/*
* 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
}
}
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.
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.