Você está na página 1de 89

Core Java

In How Many Ways can you create an object for a class in java?
There are four ways in which we can create an object for a class in java
Using New Operator: like Test t=new Test();
Using newInstance(): like Test t=(Test)Class.forName("").newInstance();
Using Clone: like Test x=new Test();
Test t=x.clone();
Using Object Deserialization : like ObjectInputStream istream=new ObjectInputStream(
some inputStream);
What are the different ways to handle exceptions?
There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those
exceptions.
What is the difference betweeen error and exception?
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These are JVM
errors and you can not repair them at runtime.
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
What is the difference between Exception & RuntimeException in Java?
RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the
Java Virtual Machine. A method is not required to declare in its throws clause any subclasses of
RuntimeException that might be thrown during the execution of the method but not caught.
The hierchy is
java.lang.Object
---java.lang.Throwable
-------java.lang.Exception
-------------java.lang.RuntimeException
What are Checked and UnChecked Exception?
Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked
Exceptions
Unchecked exceptions are those the java compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. Class Error and its subclasses also are unchecked
StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at
compile time. Runtime exceptions do not need to be. Errors often cannot be.
Is it possible to use try-catch in the finally block of java
Yes it is possible to use try catch inside the finally block of java. As a matter of fact it is a good practice to do
so as the methods called in finally block may throw an exception.

What is the difference between throw and throws keywords?


The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object
to be thrown as an argument. The exception will be caught by an enclosing try-catch block or propagated
further up the calling hierarchy. The throws keyword is a modifier of a method that denotes that an exception
may be thrown by the method. An exception can be rethrown.
User defined Exceptions are custom Exception classes defined by the user for specific purpose. A user defined
exception can be created by simply sub-classing an Exception class or a subclass of an Exception class. This
allows custom exceptions to be generated (using throw clause) and caught in the same way as normal
exceptions.
Example: class CustomException extends Exception { }

How to synchronize arraylist?


by using the method Collections.synchronizedList(); ,
ArrayList al=new ArrayList();
al.add("lolo");
al.add("polo");
al.add("hai");
Collections.synchronizedList(al);
Can we create constructor for an abstract class?
Yes , we can create Constructor for abstaract class. The constructor will be invoked while instantiating its
subclass object. The constructor can be explicitly by using super keyword.
Is it possible to override static method?
No it is not possible to override a static method. This because there is only 1 instance of a static method.
Is it possible to access non-static method from a static method

-1-
Core Java
No static method can not access non-static methods
Java has two types of methods, instance methods and static methods. A static method can be
accessed
without creating an instance of the class. If you try to use a non-static method and variable defined in
this
class then the compiler will say that non-static variable or method cannot be referenced from a static
context. Static method can call only other static methods and static variables defined in the class.
Why is Java not fully object oriented?
as Java does NOT support operator overloading and multiple inheritances Java supports multiple
inheritance through interfaces though.
In order to be fully object oriented a language must support classes,objects,inheritance and
polymorphism.
C++ is fully object oriented as it supports all the types of inheritances i.e
single,multilevel,multiple,hierarchical and multipath inheritances and if talk about polymorphism, C++
supports static binding and operator overloading which come under static polymorphism.
How can container knows that JSP has been changed ?
I created one.jsp and the result has been displayed. Next i modified one.jsp and got the new result. but how
can container know that one.jsp has got changed? By checking the "time stamp" of the jsp file
What is the difference between ApplicationServer and webserver?
Web Server -> we can run only servlets jsp and html pages but not EJB'S,Example of web server are
Tomcat.
Application Server> we can run servlets html and jsp pages and we can also run and deploy EJB's in
Application servers which is not possible in webserver
webserver is used only for jsp and servlets and for static functionality it has limited functionality and it doesn't
provide any security persistence and it doesn't support EJB and JMS and JAAS like other functionality
whereas Application server provide all functionalities.ApplicationServer will take care of all these issues like
Security Trasaction MultiThreaidng Resource pooling etc..
In webserver it is not possible.Simply speaking : AppServer = WebServer+EJB container
Write a recursive programme to reverse a string i.e given an input "catch" the output should be
"hctac"
public String reverse(String str)
{
if ((null == str) || (str.length() <= 1))
{
return str; /*End */
}
return reverse(str.substring(1)) + str.charAt(0); /* Recursion */
}
What's the difference between the methods sleep() and wait()
The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to
one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait()
is defined in the class Object and the method sleep() is defined in the class Thread.
Can you call one constructor from another if a class has multiple constructors
Yes. Use this() syntax
What would you use to compare two String variables - the operator == or the method equals()?
I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at
the same instance of a String object.
How can a subclass call a method or a constructor defined in a superclass?
To call a method use the following syntax: super.myMethod();
To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.
What is the difference between an Interface and an Abstract class?
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.
What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract
may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class
with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
What is the purpose of garbage collection in Java, and when is it used?

-2-
Core Java
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so
that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it
becomes unreachable to the program in which it is used.
Describe synchronization in respect to multithreading.
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.
Explain different way of using thread?
The thread could be implemented by using runnable interface or by inheriting from the Thread class. The
former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.
What is an Iterator?
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This
interface allows you to walk through a collection of objects, operating on each object in turn
State the significance of public, private, protected, default.
Public : Public class is visible in other packages, field is visible everywhere (class must be public too)
Private : Private variables or methods may be used only by an instance of the same class that declares the
variable or method, A private feature may only be accessed by the class that owns the feature.
Protected : Is available to all classes in the same package and also available to all subclasses of the class
that owns the protected feature.This access is provided even to subclasses that reside in a different package
from the class that owns the protected feature.
Default :What you get by default ie, without any access modifier (ie, public private or protected).It means
that it is visible to all within a particular package.
What is static in java?
Static means one per class, not one for each object no matter how many instance of a class might exist. This
means that you can use them without creating an instance of a class.Static methods are implicitly final,
because overriding is done based on the type of the object, and static methods are attached to a class, not an
object. A static method in a superclass can be shadowed by another static method in a subclass, as long as
the original method was not declared final. However, you can't override a static method with a nonstatic
method. In other words, you can't change a static method into an instance method in a subclass.
What is final?
A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when
its class is inherited. You can't change value of a final variable (is a constant).
What are pass by reference and passby value?
Pass By Reference means the passing the address itself rather than passing the value. Passby Value
means passing a copy of the value to be passed.
Difference between HashMap and HashTable?
1) HashMap allows null values as key and value whereas Hashtable doesnt allow.
2) HashMap is unsynchronized and Hashtable is synchronized.
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.
HashMap does not guarantee that the order of the map will remain constant over time.
Difference between Vector and ArrayList?
Vector is synchronized whereas arraylist is not.
What is the difference between a constructor and a method?
A constructor is a member function of a class that is used to create objects of that class. It has the same
name as the class itself, has no return type, and is invoked using the new operator.
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.

What if the main method is declared as private?


The program compiles properly but at runtime it will give "Main method not public." message.
What if the static modifier is removed from the signature of the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".
If I do not provide any arguments on the command line, then the String array of Main method will
be empty or null?
It is empty. But not null.
How can one prove that the array is not null but empty using one line of code?
Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have
thrown a NullPointerException on attempting to print args.length.
Can an application have multiple classes having main method?
Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the
Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the
multiple classes having main method.
-3-
Core Java
Can I have multiple main methods in the same class?
No the program fails to compile. The compiler says that the main method is already defined in the class.
Do I need to import java.lang package any time? Why ?
No. It is by default loaded internally by the JVM.
Can I import same package/class twice? Will the JVM load the package twice at runtime?
One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it.
And the JVM will internally load the class only once no matter how many times you import the same class.
What is Overriding?
When a class defines a method using the same name, return type, and arguments as a method in its
superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and
not the method definition from superclass. Methods may be overridden to be more public, not more private.
What are different types of inner classes?
Nested top-level classes, Member classes, Local classes, Anonymous classes
Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler
treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly
to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can
also be inner interfaces. Below as :
public class NestedClass {
static class InnerClass {
public void InnerMethod(){
System.out.println("I am in InnerMethod");
}
}
public static void main(String args[]){
System.out.println("I am in Main method");
NestedClass.InnerClass dd = new NestedClass.InnerClass();
dd.InnerMethod(); // Aceesing the innerClass
NestedClass ds = new NestedClass();
ds.nestedMethod(); // Accessing the outer class
}
}

Member classes - Member inner classes are just like other member methods and member variables and
access to the member class is restricted, just like methods and variables. This means a public member class
acts similarly to a nested top-level class. The primary difference between member classes and nested top-
level classes is that member classes have access to the specific instance of the enclosing class.
public class MemberClass {
class InnerClasss {
public void InnerMethod(){
System.out.println("I am in InnerMethodss");
}
}
public static void main(String args[]){
System.out.println("I am in Main methods");
MemberClass.InnerClasss dd = new MemberClass().new InnerClasss();
dd.InnerMethod();
}
}
Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within
the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to
implement a more publicly available interface.Because local classes are not members, the modifiers public,
protected, private, and static are not usable.
public class LocalClass {
void method() {
System.out.println("Before Local Class");
class InnerClasss { // Local class
void method1() {
System.out.println("Within Local Class");
}
}
System.out.println("After Local Class");
-4-
Core Java
InnerClasss sds = new InnerClasss();
sds.method1();
}
public static void main(String args[]){
System.out.println("I am in Main method");
LocalClass dd = new LocalClass();
dd.method();
}
}

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous
classes have no name, you cannot provide a constructor.
void initUserInterface() { // Method addWindowListener(//Method begins
//class delaration
new WindowAdapter(){
public windowClosing(WindowEvent e) {
System.exit(0);
}
}
);//Method ends
//...
}
}

What is the difference between declaring a variable and defining a variable?


In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining
means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both
definitions.
What is the default value of an object reference declared as an instance variable?
null unless we define it explicitly.
Can a top level class be private or protected?
No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not
have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler
will complain that the "modifier private is not allowed here". This means that a top level class can not be
private. Same is the case with protected.
What type of parameter passing does Java support?
In Java the arguments are always passed by value .
Does Java provide any construct to find out the size of an object?
No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in
Java.
Give a simplest way to find out the time a method takes for execution without using any profiling
tool?
Read the system time just before the method is invoked and immediately after method returns. Take the time
difference, which will give you the time taken by a method for execution.
To put it in code...
long start = System.currentTimeMillis ();
long end = System.currentTimeMillis ();
System.out.println ("Time taken for execution is " + (end - start));
Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for
execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of
processing.
What are wrapper classes?
Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper
classes. They are e.g. Integer, Character, Double etc.

Why do we need wrapper classes?


It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects
and not primitive data types. And also the wrapper classes provide many utility methods also. Because of
these resons we need wrapper classes. And since we create instances of these classes we can store them in
any of the collection classes and pass them around as a collection. Also we can pass them around as method
parameters where a method expects an object.
-5-
Core Java

How to create custom exceptions?


Your class should extend class Exception.
If I want an object of my class to be thrown as an exception object, what should I do?
The class should extend from Exception class. Or you can extend your class from some more precise exception
type also.
If my class already extends from some other class what should I do if I want an instance of my
class to be thrown as an exception object?
One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not
provide any exception interface as well.
How does an exception permeate through the code?
An unhandled exception moves up the method stack in search of a matching When an exception is thrown
from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for
matching catch block. If a matching type is found then that block will be invoked. If a matching type is not
found then the exception moves up the method stack and reaches the caller method. Same procedure is
repeated if the caller method is included in a try catch block. This process continues until a catch block
handling the appropriate type of exception is found. If it does not find such a block then finally the program
terminates.
What is the basic difference between the 2 approaches to exception handling.
1> try catch block and
2> specifying the candidate exceptions in the throws clause?
When should you use which approach?
In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if
you are in a best position to decide should be done in case of an exception. Whereas if it is not the
responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use
the second approach. In the second approach we are forcing the caller of the method to catch the exceptions,
that the method is likely to throw. This is often the approach library creators use. They list the exception in
the throws clause and we must catch them. You will find the same approach throughout the java libraries we
use.
Is it necessary that each try block must be followed by a catch block?
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.
If I write return at the end of the try block, will the finally block still execute?
Yes even if you write return as the last statement in the try block and no exception occurs, the finally block
will execute. The finally block will execute and then the control return.
If I write System.exit (0); at the end of the try block, will the finally block still execute?
No in this case the finally block will not execute because when you say System.exit (0); the control
immediately goes out of the program, and thus finally never executes.
Does the order of placing catch statements matter in the catch block?
Yes, it does. The FileNoFoundException is inherited from the IOException. So FileNoFoundException is caught
before IOException. Exception’s subclasses have to be caught first before the General Exception.

Explain Garbage collection mechanism in Java?


Garbage collection is one of the most important features of Java. The purpose of garbage collection is to
identify and discard objects that are no longer needed by a program so that their resources can be reclaimed
and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in
which it is used. Garbage collection is also called automatic memory management as JVM automatically
removes the unused variables/objects (value is null) from the memory. 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().
Does garbage collection guarantee that a program will not run out of memory?
Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs
to use up memory resources faster than they are garbage collected. It is also possible for programs to create
objects that are not subject to garbage collection.
What is the purpose of finalization?

-6-
Core Java
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup, before the
object gets garbage collected. For example, closing an opened database Connection.
Can an object’s finalize() method be invoked while it is reachable?
An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable.
However, an object’s finalize() method may be invoked by other objects.
What is serialization?
Serialization is the process of writing the state of an object to a byte stream. The serialization is a kind of
mechanism that makes a class or a bean persistent by having its properties or fields and state information
saved and restored to and from storage.
Whenever an object is to be sent over the network or saved in a file, objects are serialized.
What happens to the static fields of a class during serialization?
There are three exceptions in which serialization doesn’t necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields.

You must make sure that all the included objects are also serializable.
If any of the objects is not serializable then it throws a NotSerializableException.
What are Transient and Volatile Modifiers?
A transient variable is a variable that may not be serialized i.e. the value of the variable can’t be written to the
stream in a Serializable class.
Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be
changed unexpectedly by other parts of the program.
How to make a class or a bean serializable? How do I serialize an object to a file?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as
an object.

What invokes a thread's run() method?


After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method
when the thread is initially executed.
What is deadlock?
When two threads are waiting for each other and can’t proceed until the first thread obtains a lock on the
other thread or vice versa, the program is said to be in a deadlock.
What’s the difference between the methods sleep() and wait()?
The sleep method is used when the thread has to be put aside for a fixed amount of time. Ex: sleep(1000),
puts the thread aside for exactly one second. The wait method is used to put the thread aside for up to the
specified time. It could wait for much lesser time if it receives a notify() or notifyAll() call. Ex: wait(1000),
causes a wait of up to one second. The method wait() is defined in the Object and the method sleep() is
defined in the class Thread.
Database Questions
Q: Emp table had an employee with salary 2000. I issued an update statement to set the salary to
3000. Then I issued a create table statement. However the create table command errored out. I
want to rollback the earlier update statement. Can I do that?
ALL DDL statements are auto-commit. That means whenever you execute a DDL statement, all prior
transactions get commited. Please note that the commit is issued before excuting the DDL. So even if the
DDL statement errors out, commit would have happened.
Q: Please explain the concepts of transaction, commit and rollback
A sequence of database modifications, i.e., a sequence of insert, update, and delete statements,is called a
transaction.
These modifications are temporarily stored in the database system. They become permanent only after the
statement commit; has been issued.
As long as the user has not issued the commit statement, it is possible to undo all modifications since the last
commit. To undo modifications, one has to issue the statement rollback;.
All statements between two commits or a commit and a rollback form one transaction. Please note that all ddl
statements are autocommit.
Q: Explain the concept of NULL
In SQL NULL means the value is unknown. This is not same as 0 or the empty string ''. To check if the value in
a column is NULL we use the clause "IS NULL"
Select * from emp where sal IS NULL; This statement will return all records with salary as null. However the
statement Select * from emp where sal = NULL will not return any records.
Function nvl is used to replace the null value with some other value.
What is normalization?

-7-
Core Java
Database normalization is a data design and organization process applied to data structures based on rules
that help build relational databases. In relational database design, the process of organizing data to minimize
redundancy. Normalization usually involves dividing a database into two or more tables and defining
relationships between the tables. The objective is to isolate data so that additions, deletions, and
modifications of a field can be made in just one table and then propagated through the rest of the database
via the defined relationships.
What are the properties of the Relational tables?
Relational tables have six properties:
 Values are atomic.
 Column values are of the same kind.
 Each row is unique.
 The sequence of columns is insignificant.
 The sequence of rows is insignificant.
 Each column must have a unique name.

List few advantages of Stored Procedure.


1. Stored procedure can reduced network traffic and latency, boosting application performance.
2. Stored procedure execution plans can be reused, staying cached in SQL Server's memory, reducing server
overhead.
3. Stored procedures help promote code reuse.
4. Stored procedures can encapsulate logic. You can change stored procedure code without affecting clients.
5. Stored procedures provide better security to your data.
What are the advantages of VIEW ?
1. To protect some of the columns of a table from other users.
2. To hide complexity of a query.
3. To hide complexity of calculations.

What is difference between UNIQUE and PRIMARY KEY constraints?


A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys. The columns that
compose PK are automatically define NOT NULL, whereas a column that compose a UNIQUE is not
automatically defined to be mandatory must also specify the column is NOT NULL.
When do you use WHERE clause and when do you use HAVING clause?
HAVING clause is used when you want to specify a condition for a group function and it is written after GROUP
BY clause. The WHERE clause is used when you want to specify a condition for columns, single row functions
except group functions and it is written before GROUP BY clause if it is used.
Which is more faster - IN or EXISTS?
EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns a value.
What is difference between TRUNCATE & DELETE ?
TRUNCATE commits after deleting entire table i.e., can not be rolled back. Database triggers do not fire on
TRUNCATEDELETE allows the filtered deletion. Deleted records can be rolled back or committed.Database
triggers fire on DELETE. synchronized.
Explain UNION,MINUS,UNION ALL, INTERSECT ?
INTERSECT returns all distinct rows selected by both queries.MINUS - returns all distinct rows selected by the
first query but not by the second.UNION - returns all distinct rows selected by either queryUNION ALL -
returns all rows selected by either query, including all duplicates.
What is CYCLE/NO CYCLE in a Sequence ?
CYCLE specifies that the sequence continues to generate values after reaching either maximum or minimum
value. After pan ascending sequence reaches its maximum value, it generates its minimum value. After a
descending sequence reaches its minimum, it generates its maximum.NO CYCLE specifies that the sequence
cannot generate more values after reaching its maximum or minimum value.
Can a view be updated/inserted/deleted? If Yes under what conditions ?
A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one
or more tables then insert, update and delete is not possible.
What are the Various Master and Detail Relation ships.
The various Master and Detail Relationship are
 NonIsolated :: The Master cannot be deleted when a child is exisiting
 Isolated :: The Master can be deleted when the child is exisiting
 Cascading :: The child gets deleted when the Master is deleted
What is pseudo columns ? Name them?
pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from
pseudocolumns, but you cannot insert, update, or delete their values. This section describes these
pseudocolumns:
 CURRVAL
-8-
Core Java
 NEXTVAL
 LEVEL
 ROWID
 ROWNUM .

JSP:
1 . What is JSP? Describe its concept
JSP is a technology that combines HTML/XML markup languages and elements of Java programming Language
to return dynamic content to the Web client, It is normally used to handle Presentation logic of a web
application, although it may have business logic.
2 . What are the lifecycle phases of a JSP?
JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the
following 7 phases.
1. Page translation: -page is parsed, and a java file which is a servlet is created.
2. Page compilation: page is compiled into a class file
3. Page loading : This class file is loaded.
4. Create an instance :- Instance of servlet is created
5. jspInit() method is called
6. _jspService is called to handle service calls
7. _jspDestroy is called to destroy it when the servlet is not required.
3 . What is a translation unit?
JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include
directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this
is called a translation unit, Things to remember in a translation unit is that page directives affect the whole
unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean
cannot
declare the same bean twice in one unit.
4 . How is JSP used in the MVC model
JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the
view. The controller deals with calling the model and the business classes which in turn get the data, this data
is then presented to the JSP for rendering on to the client.
5 . What are context initialization parameters
Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for
the whole application and not specific to any servlet or JSP.
6 . What is a output comment
A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment
as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the
comment by viewing the page source from your Web browser.
7 . What is a Hidden Comment
A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden
comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the
client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you
want to hide part of your JSP page.
8 . What is a Expression
Expressions are act as place holders for language expression, expression is evaluated each time the page is
accessed.
9 . What is a Declaration
It declares one or more variables or methods for use later in the JSP source file. A declaration must contain at
least one complete declarative statement. You can declare any number of variables or methods within one
declaration tag, as long as semicolons separate them. The declaration must be valid in the scripting language
used in the JSP file.
10 . What is a Scriptlet
A scriptlet can contain any number of language statements, variable or method declarations, or expressions
that are valid in the page scripting language. Within scriptlet tags, you can declare variables or methods to
use later in the file, write expressions valid in the page scripting language, use any of the JSP implicit objects
or any object declared with a <?xml:namespace prefix = jsp />.
11 . What are the implicit objects
List them. Certain objects that are available for the use in JSP documents without being declared first. These
objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are:
1. request
2. response

-9-
Core Java
3. pageContext
4. session
5. application
6. out
7. config
8. page
9. exception
12 . What's the difference between forward and sendRedirect
When you invoke a forward request, the request is sent to another resource on the server, without the client
being informed that a different resource is going to process the request. This process occurs completely with
in the web container And then returns to the calling method. When a sendRedirect method is invoked, it
causes the web container to return to the browser indicating that a new URL should be requested. Because the
browser issues a completely new request any object that are stored as request attributes before the redirect
occurs will be lost. This extra round trip a redirect is slower than forward.
What is the difference between RequestDispatcher and sendRedirect
RequestDispatcher: server-side redirect with request and response objects.
sendRedirect : Client-side redirect with new request and response objects.

13 . What are the different scope values for the


The different scope values for <?XML:NAMESPACE PREFIX = JSP />are:
1. page
2. request
3. session
4. application
14 . Why are JSP pages the preferred API for creating a web-based client program
Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages
enable cleaner and more module application design because they provide a way to separate applications
programming from web page design. This means personnel involved in web page design do not need to
understand Java programming language syntax to do their jobs.
15 . Is JSP technology extensible
Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are
encapsulated in tag libraries.
16 . What is difference between custom JSP tags and beans
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and
then group your tags into collections called tag libraries that can be used in any number of JSP files. Custom
tags and beans accomplish the same goals â?" encapsulating complex behavior into simple and accessible
forms. There are several differences:
• Custom tags can manipulate JSP content; beans cannot.
• Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
• Custom tags require quite a bit more work to set up than do beans.
• Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one
servlet and used in a different servlet or JSP page.
• Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.
17 . How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of
using it?
You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done
by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a
single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the
servlet loaded and initialized, with the service method of each instance effectively synchronized. You can
typically control the number of instances (N) that are instantiated for all servlets implementing
SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for
variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all
requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not
recommended for normal use. There are many pitfalls, including the example above of not being able to use
%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-
safe
18 . How does JSP handle run-time exceptions
You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically
forwarded to an error processing page. For example: <%@ page errorPage="error.jsp" %> redirects the
browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within
error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true"
%> Throwable object describing the exception may be accessed within the error page via the exception
implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
- 10 -
Core Java
19 . How do I prevent the output of my JSP or Servlet pages from being cached by the browser
You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP
page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP ages
to prevent them from being cachedat the browser. You need both the statements to take care of some of the
older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
20 . How do I use comments within a JSP page
You can use JSP-style comments to selectively block out code while debugging or simply
to comment your scriptlets. JSP comments are not visible at the client. For example:
<%-- the scriptlet is now commented out
<%
out.println("Hello World");
%>
--%>
You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the
client. For example:
<!-- (c) 2004 -->
Of course, you can also use comments supported by your JSP scripting language within
your scriptlets. For example, assuming Java is the scripting language, you can have:
<%
//some comment
/**
yet another comment
**/
%>
21 . Response has already been commited error. What does it mean
This error show only when you try to redirect a page after you already have written
something in your page. This happens because HTTP specification force the header to be
set up before the lay out of the page can be shown (to make sure of how it should be
displayed, content-type="�text/html" or "text/xml" or "plain-text"� or "image/jpg",
etc.) When you try to send a redirect status (Number is line_status_402), your HTTP
server cannot send it right now if it hasn't finished to set up the header. If not starter to
set up the header, there are no problems, but if it's already begin to set up the header,
then your HTTP server expects these headers to be finished setting up and it cannot be
the case if the stream of the page is not over.. In this last case it's like you have a file
started with some output (like testing your variables.) Before you indicate that the file is
over (and before the size of the page can be setted up in the header), you try to send a
redirect status. It s simply impossible due to the specification of HTTP 1.0 and 1.1
22 . How do I use a scriptlet to initialize a newly instantiated bean
A jsp:useBean action may optionally have a body. If the body is specified, its contents
will be automatically invoked when the specified bean is instantiated. Typically, the body
will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean,
although you are not restricted to using those alone.
The following example shows the "today"� property of the Foo bean initialized to the
current date when it is instantiated. Note that here, we make use of a JSP expression
within the jsp:setProperty action.
value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>"/
>
<%-- scriptlets calling bean setter methods go here --%>"
25 . Is there a way I can set the inactivity lease period on a per-session basis
Typically, a default inactivity lease period for all sessions is set within your JSP engine
admin screen or associated properties file. However, if your JSP engine supports the
Servlet 2.1 API, you can manage the inactivity lease period on a per-session basis. This
is done by invoking the HttpSession.setMaxInactiveInterval() method, right after the
session has been created. For example:
<% session.setMaxInactiveInterval(300); %>
would reset the inactivity period for this session to 5 minutes. The inactivity interval is set in seconds.
26 . How can I set a cookie and delete a cookie from within a JSP page
A cookie, mycookie, can be deleted using the following scriptlet:
- 11 -
Core Java
<%
//creating a cookie
Cookie mycookie = new Cookie("aName","aValue");
response.addCookie(mycookie);
//delete a cookie
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>
27 . How does a servlet communicate with a JSP page
The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by
a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page,
Bean1.jsp, by means of a request dispatcher for downstream processing.
public void doPost (HttpServletRequest request, HttpServletResponse response) {
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) {
...
}
}
The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via
the useBean action.
jsp:useBean id="fBean" class="govi.FormBean" scope="request"
/ jsp:getProperty name="fBean" property="name"
/ jsp:getProperty name="fBean" property="addr"
/ jsp:getProperty name="fBean" property="age"
/ jsp:getProperty name="fBean" property="personalizationInfo" /
28 . How do I have the JSP-generated servlet subclass my own custom servlet class, instead of the
default
One should be very careful when having JSP pages extend custom servlet classes as opposed to the default
one generated by the JSP engine. In doing so, you may lose out on any advanced optimization that may be
provided by the JSP engine. In any case, your new superclass has to fulfill the contract with the JSP engine
by: Implementing the HttpJspPage interface, if the protocol used is HTTP, or implementing JspPage otherwise
Ensuring that all the methods in the Servlet interface are declared final Additionally, your servlet superclass
also needs to do the following:The service() method has to invoke the _jspService() method The init() method
has to invoke the jspInit() method The destroy() method has to invoke jspDestroy() If any of the above
conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:
<%@ page extends="packageName.ServletName" %>
29 . How can I prevent the word "null" from appearing in my HTML input text fields when I
populate them with a resultset that has null values
You could make a simple wrapper function, like
<%!
String blanknull(String s) {
return (s == null) ? "" : s;
}
%>
then use it inside your JSP form, like
<input type="text" name="shoesize" value="<%=blanknull(shoesize)% >" >
30 . How can I get to print the stacktrace for an exception occuring within my JSP page
- 12 -
Core Java
By printing out the exceptionâ?Ts stack trace, you can usually diagonse a problem better when debugging JSP
pages. By looking at a stack trace, a programmer should be able to discern which method threw the exception
and which method called that method. However, you cannot print the stacktrace using the JSP out implicit
variable, which is of type JspWriter. You will have to use a PrintWriter object instead. The following snippet
demonstrates how you can print a stacktrace from within a JSP error page:
<%@ page isErrorPage="true" %>
<%
out.println(" ");
PrintWriter pw = response.getWriter();
exception.printStackTrace(pw);
out.println(" ");
%>
31 . How do you pass an InitParameter to a JSP
The JspPage interface defines the jspInit() and jspDestroy() method which the page writer can use in their
pages and are invoked in much the same manner as the init() and destory() methods of a servlet. The
example page below enumerates through all the parameters and prints them to the console.
<%@ page import="java.util.*" %>
<%!
ServletConfig cfg =null;
public void jspInit(){
ServletConfig cfg=getServletConfig();
for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
String name=(String)e.nextElement();
String value = cfg.getInitParameter(name);
System.out.println(name+"="+value);
}
}
%>
33 . Can we implement an interface in a JSP
No
34 . What is the difference between ServletContext and PageContext
ServletContext: Gives the information about the container.
PageContext: Gives the information about the Request
35 . What is the difference in using request.getRequestDispatcher() and
context.getRequestDispatcher()
request.getRequestDispatcher(path): In order to create it we need to give the relative path of the
resource,
context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the
resource.
36 . How to pass information from JSP to included JSP
Using <%jsp:param> tag.
37 . What is the difference between directive include and jsp include
<%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic
content or static content during runtime.
39 . How do I mix JSP and SSI #include
If you're just including raw HTML, use the #include directive as usual inside your .jsp file.
But it's a little trickier if you want the server to evaluate any JSP code that's inside the included file. If your
data.inc file contains jsp code you will have to use
<%@ vinclude="data.inc" %>
The is used for including non-JSP files.

- 13 -
Core Java

What is Struts?
The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets,
JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages
application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller
(MVC) design paradigm.
Struts provides its own Controller component and integrates with other technologies to provide the Model and
the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well
as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts
works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other
presentation systems.
What is Jakarta Struts Framework?
Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of
web based applications. Jakarta Struts is robust architecture and can be used for the development of
application of any size. Struts framework makes it much easier to design scalable, reliable Web applications
with Java.
What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts
Framework this class plays the role of controller. All the requests to the server goes through the controller.
Controller is responsible for handling all the requests.
How you will make available any Message Resources Definitions file to the Struts Framework
Environment?
T Message Resources Definitions file are simple .properties files and these files contains the messages that can
be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file
through <message-resources /> tag.
Example:
<message-resources parameter=\"MessageResources\" />.
What is Action Class?
The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class
is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and
overwrite the execute() method. In the Action Class all the database/business processing are done. It is
advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes
the parameterized class to Action Form using the execute() method. The return type of the execute method is
ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the
returned ActionForward object.
What is ActionForm?
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the
session state for web application and the ActionForm object is automatically populated on the server side with
data entered from a form on the client side.
What is Struts Validator Framework?
Struts Framework provides the functionality to validate the form data. It can be use to validate the data on
the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used
validate the form data on the client browser. Server side validation of form can be accomplished by sub
classing your From Bean with DynaValidatorForm class.

- 14 -
Core Java
The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the
Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The
Validator framework comes integrated with the Struts Framework and can be used without doing any extra
settings.
Give the Details of XML files used in Validator Framework?
The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The
validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to
define the form specific validations. The validation.xml defines the validations applied to a form bean.
How you will display validation fail errors on jsp page?
Following tag displays all the errors:
<html:errors/>
How you will enable front-end validation based on the xml in validation.xml?
The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the
code: <html:javascript formName=\"logonForm\" dynamicJavascript=\"true\" staticJavascript=\"true\" />
generates the client side java script for the form \"logonForm\" as defined in the validation.xml file. The
<html:javascript> when added in the jsp file generates the client site validation script.
How to get data from the velocity page in a action class?
We can get the values in the action classes by using data.getParameter(\"variable name defined in the
velocity page\");
What Is the Struts Framework?
The Struts Framework is a standard for developing well-architected Web applications. It has the following
features:
 Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:
o Model: application state
o View: presentation of data (JSP, HTML)
o Controller: routing of the application flow
 Implements the JSP Model 2 Architecture
 Stores application routing information and request mapping in a single core file, struts-config.xml
The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the
developer.
Architecture Overview

All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration file struts-
config.xml is used by the controller to determine the routing of the flow. This flows consists of an
alternation between two transitions:
From View to Action A user clicks on a link or submits a form on an HTML or JSP page. The controller
receives the request, looks up the mapping for this request, and forwards it to an
action. The action in turn calls a Model layer (Business layer) service or function.

From Action to View After the call to an underlying function or service returns to the action class, the action
forwards to a resource in the View layer and a page is displayed in a web browser.

- 15 -
Core Java
The diagram below describes the flow in more detail:

1. User clicks on a link in an HTML page.


2. Servlet controller receives the request, looks up mapping information in struts-config.xml, and routes
to an action.
3. Action makes a call to a Model layer service.
4. Service makes a call to the Data layer (database) and the requested data is returned.
5. Service returns to the action.
6. Action forwards to a View resource (JSP page)
7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.
8. JSP file is invoked and sent to the browser as HTML.
9. User is presented with a new HTML page in a web browser.
Struts Components
The Controller
This receives all incoming requests. Its primary function is the mapping of a request URI to an action class
selecting the proper application module. It's provided by the framework.
The struts-config.xml File
This file contains all of the routing and configuration information for the Struts application. This XML file needs
to be in the WEB-INF directory of the application.
Action Classes
It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs and
business services. Actions process a request and return an ActionForward object that identifies the next
component to invoke. They're part of the Controller layer, not the Model layer.
View Resources
View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource bundles,
JavaBeans, and Struts JSP tags.
ActionForms
These greatly simplify user form validation by capturing user data from the HTTP request. They act as a
"firewall" between forms (Web pages) and the application (actions). These components allow the validation of
user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed.
Model Components
The Struts Framework has no built-in support for the Model layer. Struts supports any model components:
 JavaBeans
 EJB
 CORBA
 JDO
 any other
Struts, an MVC 2 implementation
Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. This
definition implies that Struts is a framework, rather than a library, but Struts also contains an extensive tag
library and utility classes that work independently of the framework. Figure 5 displays an overview of Struts.

- 16 -
Core Java

Struts overview
 Client browser
An HTTP request from the client browser creates an event. The Web container will respond with an HTTP
response.
 Controller
The Controller receives the request from the browser, and makes the decision where to send the request. With
Struts, the Controller is a command design pattern implemented as a servlet. The struts-config.xml file
configures the Controller.
 Business logic
The business logic updates the state of the model and helps control the flow of the application. With Struts
this is done with an Action class as a thin wrapper to the actual business logic.
 Model state
The model represents the state of the application. The business objects update the application state.
ActionForm bean represents the Model state at a session or request level, and not at a persistent level. The
JSP file reads information from the ActionForm bean using JSP tags.
 View
The view is simply a JSP file. There is no flow logic, no business logic, and no model information -- just tags.
Tags are one of the things that make Struts unique compared to other frameworks like Velocity.
1.What is MVC?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface
from business logic and data.
Model : The model contains the core of the application's functionality. The model encapsulates the state of
the application. Sometimes the only functionality it contains is state. It knows nothing about the view or
controller
View: The view provides the presentation of the model. It is the look of the application.
Controller:The controller reacts to the user input. It creates and sets the model.
2.What is a framework?
A framework is made up of the set of classes which allow us to use a library in a best possible way for a
specific requirement.
3.What is Struts framework?
Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-
2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the
development of application of any size. Struts framework makes it much easier to design scalable, reliable
Web applications with Java.
4.What are the components of Struts?
Struts components can be categorize into Model, View and Controller:
Model: Components like business logic /business processes and data are the part of model.
View: HTML, JSP are the view components.
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle
all the requests.
5.What are the core classes of the Struts Framework?
Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs.

6.What is ActionServlet?
ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller
component that handles client requests and determines which Action will process each received request. It
serves as an Action factory – creating specific Action classes based on user’s request.
7.What is role of ActionServlet?
ActionServlet performs the role of Controller:
← Process user requests

- 17 -
Core Java
← Determine what the user is trying to achieve according to the request
← Pull data from the model (if necessary) to be given to the appropriate view,
← Select the proper view to respond to the user
← Delegates most of this grunt work to Action classes
← Is responsible for initialization and clean-up of resources
8.What is the ActionForm? ActionForm is javabean which represents the form inputs containing the request
parameters from the View referencing the Action bean.
9.What are the important methods of ActionForm?
The important methods of ActionForm are : validate() & reset().
10.Describe validate() and reset() methods ?
validate() : Used to validate properties after they have been populated; Called before FormBean is handed to
Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate()
method.
reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm.
The purpose of this method is to reset all of the ActionForm's data members prior to the new request values
being set.
public void reset() {}

11.What is ActionMapping?
Action mapping contains all the deployment information for a particular Action bean. This class is to determine
where the results of the Action will be sent once its processing is complete.

12.How is the Action Mapping specified ?


We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates
ActionMapping object from <ActionMapping> configuration element of struts-config.xml file

<action-mappings>
<action path="/submit"
type="submit.SubmitAction"
name="submitForm"
input="/submit.jsp"
scope="request"
validate="true">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/error.jsp"/>
</action>
</action-mappings>

13.What is role of Action Class?


An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the
corresponding business logic that should be executed to process this request.

14.In which method of Action class the business logic is executed ?


In the execute() method of Action class the business logic is executed.

public ActionForward execute(


ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;

- 18 -
Core Java
execute() method of Action class:
Perform the processing required to deal with this request
Update the server-side objects (Scope variables) that will be used to create the next page of the
user interface
Return an appropriate ActionForward object
15.What design patterns are used in Struts?
Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command
design pattern and the action classes use the adapter design pattern. The process() method of the
RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design
patterns.
Service to Worker
Dispatcher View
Composite View (Struts Tiles)
Front Controller
View Helper
Synchronizer Token
16.Can we have more than one struts-config.xml file for a single Struts application?
Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as
follows:
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml,
/WEB-INF/struts-admin.xml,
/WEB-INF/struts-config-forms.xml
</param-value>
</init-param>
.....
<servlet>

18.What is the difference between session scope and request scope when saving formbean ?
when the scope is request,the values of formbean would be available for the current request.
when the scope is session,the values of formbean would be available throughout the session.

17.What is the directory structure of Struts application?


The directory structure of Struts application :

- 19 -
Core Java

19.What are the important tags of struts-config.xml ?


The five important sections are:

- 20 -
Core Java

20.What are the different kinds of actions in Struts?


The different kinds of actions in Struts are:
← ForwardAction
← IncludeAction
← DispatchAction
← LookupDispatchAction
← SwitchAction
21.What is DispatchAction?
The DispatchAction class is used to group related actions into one class. Using this class, you can have a
method for each logical action compared than a single execute method. The DispatchAction dispatches to one
of the logical actions represented by the methods. It picks a method to invoke based on an incoming request
parameter. The value of the incoming parameter is the name of the method that the DispatchAction will
invoke.

22.How to use DispatchAction?


To use the DispatchAction, follow these steps :
← Create a class that extends DispatchAction (instead of Action)
← In a new class, add a method for every function you need to perform on the service – The method has
the same signature as the execute() method of an Action class.
← Do not override execute() method – Because DispatchAction class itself provides execute() method.

- 21 -
Core Java
← Add an entry to struts-config.xml
23.What is the use of ForwardAction?
The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses
Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller
and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request
to another resource in your application, such as a Servlet that already does business logic processing or even
another JSP page. By using this predefined action, you don’t have to write your own Action class. You just
have to set up the struts-config file properly to use ForwardAction.

24.What is IncludeAction?
The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use
the IncludeAction class to include another resource in the response to the request being processed.

25.What is the difference between ForwardAction and IncludeAction?


The difference is that you need to use the IncludeAction only if the action is going to be included by another
action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a
Servlet that already does business logic processing or even another JSP page.

26.What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to
get the key and then gets the method whose name is associated with the key into the Resource Bundle.

27.What is the use of LookupDispatchAction?


LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end,
but by the Locale independent key into the resource bundle. Since the key is always the same, the
LookupDispatchAction shields your application from the side effects of I18N.

31.What is DynaActionForm?
A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties
(configured in configuration file), without requiring the developer to create a Java class for each type of form
bean.

32.What are the steps need to use DynaActionForm?


Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to
make changes in two places:
In struts-config.xml: change your <form-bean> to be an org.apache.struts.action.DynaActionForm
instead of some subclass of ActionForm
<form-bean name="loginForm"type="org.apache.struts.action.DynaActionForm" >
<form-property name="userName" type="java.lang.String"/>
<form-property name="password" type="java.lang.String" />
</form-bean>

In your Action subclass that uses your form bean:


← import org.apache.struts.action.DynaActionForm
← downcast the ActionForm parameter in execute() to a DynaActionForm
← access the form fields with get(field) rather than getField()

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

- 22 -
Core Java

import org.apache.struts.action.DynaActionForm;

public class DynaActionFormExample extends Action {


public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm loginForm = (DynaActionForm) form;
ActionMessages errors = new ActionMessages();
if (((String) loginForm.get("userName")).equals("")) {
errors.add("userName", new ActionMessage(
"error.userName.required"));
}
if (((String) loginForm.get("password")).equals("")) {
errors.add("password", new ActionMessage(
"error.password.required"));
}
...........

33.How to display validation errors on jsp page?


<html:errors/> tag displays all the errors. <html:errors/> iterates over ActionErrors request attribute.

34.What are the various Struts tag libraries?


The various Struts tag libraries are:
HTML Tags
Bean Tags
Logic Tags
Template Tags
Nested Tags
Tiles Tags
35.What is the use of <logic:iterate>?
<logic:iterate> repeats the nested body content of this tag over a specified collection.

<table border=1>
<logic:iterate id="customer" name="customers">
<tr>
<td><bean:write name="customer" property="firstName"/></td>
<td><bean:write name="customer" property="lastName"/></td>
<td><bean:write name="customer" property="address"/></td>
</tr>
</logic:iterate>
</table>

36.What are differences between <bean:message> and <bean:write>


<bean:message>: is used to retrive keyed values from resource bundle. It also supports the ability to
include parameters that can be substituted for defined placeholders in the retrieved string.

- 23 -
Core Java
<bean:message key="prompt.customer.firstname"/>

<bean:write>: is used to retrieve and print the value of the bean property. <bean:write> has no body.
<bean:write name="customer" property="firstName"/>

37.How the exceptions are handled in struts?


Exceptions in Struts are handled in two ways:
Programmatic exception handling : Explicit try/catch blocks in any code that can throw exception.
It works well when custom value (i.e., of variable) needed when error occurs.
Declarative exception handling :You can either define <global-exceptions> handling tags in your
struts-config.xml or define the exception handling tags within <action></action> tag. It works well when
custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.
<global-exceptions>
<exception key="some.key"
type="java.lang.NullPointerException"
path="/WEB-INF/errors/null.jsp"/>
</global-exceptions>

or
<exception key="some.key"
type="package.SomeException"
path="/WEB-INF/somepage.jsp"/>

38.What is difference between ActionForm and DynaActionForm?


An ActionForm represents an HTML form that the user interacts with over one or more pages. You will
provide properties to hold the state of the form with getters and setters to access them. Whereas, using
DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their
type are declared in the struts-config.xml
The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying
as the Struts Config file grow larger.
The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time
checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config
file.
ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and
encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property
access is no different than using request.getParameter( .. ).
DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery
that can be avoided.
39.How can we make message resources definitions file available to the Struts framework
environment?
We can make message resources definitions file (properties file) available to Struts framework environment by
adding this file to struts-config.xml.
<message-resources parameter="com.login.struts.ApplicationResources"/>

40.What is the life cycle of ActionForm?


The lifecycle of ActionForm invoked by the RequestProcessor is as follows:
Retrieve or Create Form Bean associated with Action
"Store" FormBean in appropriate scope (request or session)
Reset the properties of the FormBean
Populate the properties of the FormBean
Validate the properties of the FormBean
Pass FormBean to Action
Why it called Struts?
Because the designers want to remind us of the invisible underpinnings that hold up our houses, buildings,
bridges, and ourselves when we are on stilts. This excellent description of Struts reflect the role the Struts
plays in developing web applications.

- 24 -
Core Java
What is the design role played by Struts?
The role played by Structs is controller in Model/View/Controller(MVC) style. The View is played by JSP and
Model is played by JDBC or generic data source classes. The Struts controller is a set of programmable
components that allow developers to define exactly how the application interacts with the user.
How Struts control data flow?
Struts implements the MVC/Layers pattern through the use of ActionForwards and ActionMappings to keep
control-flow decisions out of presentation layer.
What configuration files are used in Struts?
ApplicationResources.properties
struts-config.xml
These two files are used to bridge the gap between the Controller and the Model.
What helpers in the form of JSP pages are provided in Struts framework?
--struts-html.tld
--struts-bean.tld
--struts-logic.tld
What is Action Class?
The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class
is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and
overwrite the execute() method. In the Action Class all the database/business processing are done. It is
advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes
the parameterized class to Action Form using the execute() method. The return type of the execute method is
ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the
returned ActionForward object.
Write code of any Action Class?
Here is the code of Action Class that returns the ActionForward object.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class TestAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
return mapping.findForward(\"testAction\");
}
}
What is ActionForm?
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the
session state for web application and the ActionForm object is automatically populated on the server side with
data entered from a form on the client side.
How do I use JavaScript to ...
Struts is mainly a server-side technology. We bundled in some JSP tags to expose the framework components
to your presentation page, but past that, the usual development process applies.
Interactive pages require the use of JavaScript. (That's why it was invented.) If you want things popping up or
doing this when they click that, you are outside the scope of Struts and back into the web development
mainstream.
You use JavaScript with Struts the same way you use with any presentation page. Since JavaScript is a client-
side technology, you can use simple relative references to your scripts. If you need to fire a JavaScript from a
HTML control, the Struts HTML tags have properties for the JavaScript events.
A very good JavaScript resource is Matt Kruse's site at http://www.mattkruse.com/javascript/ Do I need to
implement reset and set all my form properties to their initial values?
No. You need to set checkbox properties to false if the ActionForm is being retained in session scope. This is
because an unchecked box does not submit an attribute. Only checked boxes submit attributes. If the form is
in session scope, and the checkbox was checked, there is no way to turn it back off without the reset method.
Resetting the properties for other controls, or for a request scope form, is pointless. If the form is in request
scope, everything already just started at the initial value.

- 25 -
Core Java
Can I have an Action without a form?
Yes. If your Action does not need any data and it does not need to make any data available to the view or
controller component that it forwards to, it doesn't need a form. A good example of an Action with no
ActionForm is the LogoffAction in the struts example application:
<action path="/logoff"
type="org.apache.struts.webapp.example.LogoffAction">
<forward name="success" path="/index.jsp"/>
</action>
This action needs no data other than the user's session, which it can get from the Request, and it doesn't
need to prepare any view elements for display, so it does not need a form.
How can I avoid validating a form before data is entered?
The simplest way is to have two actions. The first one has the job of setting the form data, i.e. a blank
registration screen. The second action in our writes the registration data to the database. Struts would take
care of invoking the validation and returning the user to the correct screen if validation was not complete.
The EditRegistration action in the struts example application illustrates this:
< action path="/editRegistration">
type="org.apache.struts.webapp.example.EditRegistrationAction"
attribute="registrationForm"
scope="request"
validate="false">
<forward name="success path="/registration.jsp"/>
</action>
When the /editRegistration action is invoked, a registrationForm is created and added to the request, but its
validate method is not called. The default value of the validate attribute is true, so if you do not want an
action to trigger form validation, you need to remember to add this attribute and set it to false.
How can I 'chain' Actions?
Chaining actions can be done by simply using the proper mapping in your forward entries in the struts-
config.xml file. Assume you had the following two classes:
/* com/AAction.java */

public class AAction extends Action


{
public ActionForward
execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception
{
// Do something

return mapping.findForward("success");
}
}

/* com/BAction.java */
...

public class BAction extends Action


{
public ActionForward
execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception
{
// Do something else

return mapping.findForward("success");
}
- 26 -
Core Java
}

Then you can chain together these two actions with the Struts configuration as shown in the following
excerpt:

<action-mappings type="org.apache.struts.action.ActionMapping">
<action path="/A"
type="com.AAction"
validate="false">
<forward name="success" path="/B.do" />
</action>
<action path="/B"
type="com.BAction"
scope="session"
validate="false">
<forward name="success" path="/result.jsp" />
</action>
</action-mappings>

Here we are assuming you are using a suffix-based (.do) servlet mapping, which is recommended since
module support requires it. When you send your browser to the web application and name the action A.do
(i.e. http://localhost:8080/app/A.do) it will execute AAction.execute(), which will then forward to the
"success" mapping.
This causes the execution of BAction.execute() since the entry for "success" in the configuration file uses
the .do suffix.
Of course it is also possible to chain actions programmatically, but the power and ease of being able to
"reroute" your web application's structure using the XML configuration file is much easier to maintain.
As a rule, chaining Actions is not recommended. If your business classes are properly factored, you should be
able to call whatever methods you need from any Action, without splicing them together into a cybernetic
Rube Goldberg device.
If you must chain Actions, be aware of the following: calling the second Action from the first Action has the
same effect as calling the second Action from scratch. If both of your Actions change the properties of a
formbean, the changes made by the first Action will be lost because Struts calls the reset() method on the
formbean when the second Action is called.
Declarative Exception Handling
If you have developed web applications long enough, you will realize a recurring pattern emerges: when the
backend (e.g. the EJB tier) throws you an exception, you nearly always need to display an error page
corresponding to the type of that exception. Sooner or later, you will come up with a mechanism to use a
lookup table (e.g. an HashMap) to lookup an error page from the exception class.
Struts 1.1 now provides a similar but more powerful mechanism to declare exception handling. In Struts 1.1,
you can declare in the struts-config.xml the associations between an exception class and an exception
handler. Using the default exception handler included in Struts, you can also specify the path of the error
pages. With this information, Struts will automatically forward to the specified pages when an uncaught
exception is thrown from an Action.
Like other facilities in Struts, the exception handlers are pluggable. You can write and define your own handler
classes if needed.
why do we typecast ActionForm into our plain java bean class in Action class? What is the reason?
Bcos in the Actoin class we have execute method ..it consits of ActionForm parameter...our bean class extends
the ActionForm... so we can type cast the ActionForm to Bean and depending on the requirement we can use
the methods in the bean class.
What are the contents of web.xml and struts-config...
web.xml is used for the deployment descriptor for web applications where struts-config.xme is used for
deployment descripror for struts application.
Struts-config.xml is used for making connection between view & controller where as web.xml is used for
making connection between web container & web application
What is struts flow? Explain in detail
whenever client send request first it goes to CONTROLLER part(ActionServlet)it reads the request data&
decides about which action should be performed to process the client request after that it forwards to the
appropriate action class(MODEL part)where the functionality code(bussiness logic) will be there, from this
MODEL part the control goes back to CONTROLLER part from here the appropriate jsp pages(VIEW part) can
be picked up for presenthing(displaying) the result on the clients browser.
when ever client sends a request, first it will reads the web.xml and creates a action servlet object and
wc(webcontainer) calls the init()on action servlet.The struts code that is part of a init()reads the information
- 27 -
Core Java
that is available in the StrutsConfig.xml and executes the appropriate action class with the help of action
mapping that is part of a SC.xml.
Struts is a framework with set of cooperating classes, servlets and JSP tags that make up a reusable MVC 2
design.

> Client (Browser): A request from the client browser creates an HTTP request. The Web container will
respond to the request with an HTTP response, which gets displayed on the browser.
> Controller (ActionServlet class and Request Processor class): The controller receives the request from the
browser, and makes the decision where to send the request based on the struts-config.xml.
Design pattern: Struts controller uses the command design pattern by calling the Action classes based on the
configuration file struts-config.xml and the RequestProcessor class?s process() method uses template
What is the difference between a normal servlet and action servlet?
Both a normal servlet and action sevlet are same, which extend HttpServlet and implement the servlet
lifecycle methods..
Normal Servlet and Action servlet are same but Action servlet consists of logic for forwarding the request to
corresponding action class
What are the drawbacks of Struts
In struts , their is no facility of backward flow.
Suppose we are in page 1 and when we submit it calls action mapping page2.Their may be lot of variable
stored in session , which is available to page2.Now we wish to go page1 from page 2, for this we have to call
the action mapping of page1. But struts flow is always in forward direction. So when we call page 1, values
stored in session never get reversed.So it reduces the performance.

To resolve this problem of struts, Their is a framework called Web Flow Nevigation Manager(WFNM) of
Sourgeforge.net.This framework can be integrated with struts.
What we will define in Struts-config.xml file. And explain their purpose?
Struts-Config.xml is one of the most important part of any web application based on Sturts. This file is
responsible for instructing the Struts what forms are available, what actions are available, and also allows a
number of plug-in models to be added to the base Struts package. It can contain Data Source
Configuration,Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions, Message
Resources Definitions etc.
In struts-config.xml we define Date Sources / Form Beans / Global Exceptions / Global Forwards / Action
Mappings / Message Resources / Plug-ins
Who will run the execute method in struts?
The web Container calls the Execute Method with the help of the Action class we write.
How you will handle errors and exceptions using Struts?
Struts exception handling can be done by two ways:

1. Declarative (using struts features via struts-config.xml)

<global-exceptions>
<exception
type="hansen.playground.MyException2"
key ="errors.exception2"
path="/error.jsp"/>
</global-exceptions>
This makes coding in the Action class very simple
Since the execute method declares throws Exception we don't need a try-catch block.

Struts saves the exception using one of its global constants. You may use the field G lobals.EXCEPTION_KEY
to retrieve it from the request object.

2. Programmatic (using the usual try-catch exception handling in Action Class)


We can Handle the errors by holding them into ActionError or ActionErrors classes defined by struts
Framework. The other way around is by using the methods say saveErrors()....etc defined in Action class and
can throw the error messages.
How Struts control data flow?
Struts implements the MVC/Layers pattern through the use of ActionForwards and ActionMappings to keep
control-flow decisions out of presentation layer.
Explain about the tag?
This tag is present in the HTML library provided by Struts. This tag informs the browser to pretend that the
original tag is located at somewhere other than the current url. This tag is responsible in creating a base tag
which gives a false impression to the user via browser about the exact location of the url.
- 28 -
Core Java

Ques And Ans.


Difference between array and arraylist.
1 . Array is the object and it stores the object of same type
Eg : Its stores complete integer types or string types
int[] IntArray = new int[3];
string[] StringArray = new StringArray[2];
Arraylist is the collection in which we can store the objects of any data type.
Eg : Arraylist Arr = new Arraylist()
Arr.Add(13); // Integer Type
Arr.Add(10); // String Type

2 . Arrays has the Fixed Lenght where as the Arraylist varies the leghth as the objects Added.

Array is the one which can save similar data typed elements.And the size is limited.
Arraylist is a collection which is capable of saving different data typed objects,And is growable.

What is HashMap and Map?


Map is Interface and Hashmap is class that implements that and its not serialized HashMap is non serialized
and Hashtable is serialized.

Difference Between Arraylist and vector


1. Arraylist is not synchronized while vector is.
2. Arraylist has no default size while vector has a default size of 10.
3. Arraylist don't define any increment size while vector does.
Q1 ) What is difference between ArrayList and HashMap ?
Ans : An ArrayList is a collection that has a hidden array that is secretly extended on need.
A HashMap is a collection that tries to give access to all contents by their hash-key.
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all
elements, including null. In addition to implementing the List interface, this class provides methods to
manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to
Vector, except that it is unsynchronized.)
Q 2 ) What is Implicit objects in jsp and How Many types these impl objects
Ans : ImplictObject API
1)out =JspWriter
2)Request =HttpServletRequest
3)Response =HttpServletResponse
4)session =HttpSession
5)page =Object
6)PageContext =PageContext
7)Application =ServletContext
8)Config =ServletConfig
9)Exception =JspException

using the implict objects you can take the advantage of the servletness eventhough you are not directly using
the servlet yourself
These are used for different purposes and actually u no need to create these objects in JSP. JSP container will
create these objects automatically.
You can directly use these objects.
Example:
If i want to put my username in the session in JSP.
JSP Page:

In the about page, i am using session object. But this session object is not declared in JSP file, because, this is
implicit object and it will be created by the jsp container.
If u see the java file for this jsp page in the work folder of apache tomcat, u will find these objects are
created.

- 29 -
Core Java

Q 3 ) What is difference between SendRedirect and forward action


Ans :
1)In the case of forward() the server will redirect to the next page but in the case of sendRedirct() the server
will inform the browser to redirect the url to the next page.
2)The main diff b/w forward and send redirect is forward is done at serverside where as send redirect is done
at clientside.
3)sendRedirect() means it's client side redirect at that time new parameters can be added.(i.e HttpRequest,
HttpResponse) forward() meand it's server side redirect at that time same parameters can be used.
4)forward() can be used forwarding the request from one servlet to jsp.(i.e with in the container). redirect()
can be used redirecting the one jsp to another jsp(i.e different containers).
5)When we use forward, then servlet container forwards all request to the target page. but in the case
sendRedirect,container makes a new request to the target Page. So in forward , url link doesn't change but in
sendRedirect url line change . Because container makes a new request, sendRedirect is much slower than
forward.
6) sendRedirect() can be used to send a request with in the server or in other server. forward() can be used
to send request in the same server.

Q 4 ) what is Servlet and what is its uses.


Ans : Servlets are managed components. They are managed by web container. Of the various responsibilities
of web container, servlet life cycle management is the most important one. A servlet is managed through a
well defined life cycle that defines how it is loaded, instantiated ad initialized, handles requests from clients
and how it is taken out of service. The servlet life cycle methods are defined in the javax.servlet.Servlet
interface of the Servlet API that all Servlets must implement directly or indirectly by extending GenericServlet
or HttpServlet abstract classes. Most of the servlet you develop will implement it by extending HttpServlet
class.
The servlet life cycle methods defined in Servlet interface are init(), service() and destroy(). The
life cycle starts when container instantiates the object of servlet class and calls the init() method, and ends
with the container calling the destroy() method.
The signature of this methods are shown below.
public void init(ServletConfig config) throws ServletException
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
The servlet life cycle consists of four steps, instantiation, initialization, request handling and end of service.
Each of these steps is explained below.
Loading and instantiation
During this step, web container loads the servlet class and creates a new instance of the servlet. The
container can create a servlet instance at container startup or it can delay it until the servlet is needed to
service a request.
Initialization
During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by calling
the init() method. The container passes an object implementing the ServletConfig interface via the init()
method. This configuration object allows the servlet to access name-value initialization parameters from the
web application’s deployment descriptor (web.xml) file. The container guarantees that the init() method will
be called before the service() method is called.
The init() method is typically used to perform servlet initialization, creating or loading objects that are used by
the servlet in the handling of its requests.
The init() method is commonly used to perform one time activity. One of the most common use of init()
method is to setup the database connection or connection pool.

- 30 -
Core Java
Request handling
After a servlet is properly initialized, it is ready to handle the client requests. If the container has a request for
the servlet, it calls the servlet instance’s service() method. The request and response information is wrapped
in ServletRequest and ServletResponse objects respectively, which are then passed to the servlet's service()
method. In the case of an HTTP request, the objects provided by the container are of types
HttpServletRequest and HttpServletResponse.
Service() method is responsible for processing the incoming requests and generating the response.
End of service
When the servlet container determines that a servlet should be removed from service, it calls the destroy ()
method of the Servlet instance to allow the servlet to release any resources it is using. The servlet container
can destroy a servlet because it wants to conserve some memory or server itself is shutting down. Before the
servlet container calls the destroy() method, it allows any threads that are currently running in the service
method of the servlet to complete execution, or exceed a server defined time limit. Once the destroy()
method has completed, the container will release the servlet instance for garbage collection. If it needs
another instance of the servlet to process requests it creates the new instance of the servlet and life cycle
starts again.
Destroy() method is used to release any resources it is using. The most common use of destroy() method is
to close the database connections.

Q 5 ) Difference between doget and dopost and Service method in Servlet.


Ans : 1. In doGet() u submit the request by appending the URL while in doPost() request is submitted via
form.
2.Since doGet() appends the link it is not safe for request containing passwords etc. while doPost() uses form
hens it is safe.
3.You can send only limited data in doGet() while unlimited data in doPost() .
4.doGet() request could used like a bookmark as it uses URL but doPost() can't be used as bookmark.
5.doPost() is Idempotent i.e if the user requests for some thing & later he changes his decision & rerequests
to make some changes in previous request doPost() gets failed in that case while doGet() is useful in such
cases.
doGet is called in response to an HTTP GET request. This happens when users click on a link, or enter a URL
into the browser's address bar. It also happens with some HTML FORMs (those with METHOD="GET" specified
in the FORM tag).
doPost is called in response to an HTTP POST request. This happens with some HTML FORMs (those with
METHOD="POST" specified in the FORM tag).
Both methods are called by the default (superclass) implementation of service in the HttpServlet base class.
You should override one or both to perform your servlet's actions. You probably shouldn't override service().

Q 7 ) What is classes are used in Struts.


Q 8 ) collection in java.
Collection is the interface. which can be implemented List,set,Queue.This interface contain only instance
methods.
Collection is the class .This class contain utility methods such as all algorithm oriented methods.This class
contain only static methods.

Q 9 ) Connection Pooling and what is default time for connections.


Ans : Please see the Links: http://www.snaq.net/java/DBPool/

Q 10) What is joins in database.


Ans : (1)Inner join: Equi-join,Natural join,Cross join
The INNER JOIN keyword return rows when there is at least one match in both tables.
SELECT * FROM employee
INNER JOIN department ON employee.DepartmentID = department.DepartmentID
as like above as
SELECT * FROM employee, department
WHERE employee.DepartmentID = department.DepartmentID
(A) :Equi-join:

- 31 -
Core Java
SELECT * FROM employee
INNER JOIN department ON employee.DepartmentID = department.DepartmentID
as same as
SELECT * FROM employee INNER JOIN department USING (DepartmentID)
(B) :Natural join :
SELECT * FROM employee NATURAL JOIN department
(c) :Cross join :Formula as A × B.
SELECT * FROM employee CROSS JOIN department
Same as above :
SELECT * FROM employee, department;

(2)Outer joins :Left outer join,Right outer joins,Full outer join


(A) :Left outer join :
The left outer join returns all the values from the left table, plus matched values from the right table
OR The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no
matches in the right table(table_name2).
SELECT * FROM employee LEFT OUTER JOIN department
ON employee.DepartmentID = department.DepartmentID
(B):Right outer joins
A right outer join returns all the values from the right table and matched values from the left .
OR The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches
in the left table (table_name1).
SELECT * FROM employee RIGHT OUTER JOIN department
ON employee.DepartmentID = department.DepartmentID
(C): Full outer join
A full outer join combines the results of both left and right outer joins.
The joined table will contain all records from
both tables, and fill in NULLs for missing matches on either side. OR The FULL JOIN keyword return rows when
there is a match
in one of the tables.

SELECT * FROM employee


FULL OUTER JOIN department ON employee.DepartmentID = department.DepartmentID
(3)Self-join :
SELECT F.EmployeeID, F.LastName, S.EmployeeID, S.LastName, F.Country
FROM Employee F, Employee S WHERE F.Country = S.Country
AND F.EmployeeID < S.EmployeeID ORDER BY F.EmployeeID, S.EmployeeID;

JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
FULL JOIN: Return rows when there is a match in one of the tables

The SQL UNION operator combines two or more SELECT statements.


SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL.
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
The SQL SELECT INTO Statement :
SELECT * INTO new_table_name [IN externaldatabase] FROM old_tablename
SQL SELECT INTO - Joined Tables:
SELECT Persons.LastName,Orders.OrderNo INTO Persons_Order_Backup
FROM Persons INNER JOIN Orders ON Persons.P_Id=Orders.P_Id

11) How to build the war file from myeclipse.


Ans : MyEclipse -->File --> export --> Select as web and war file,it is depend on requirement and you can
also select the .ear file from java EE --> make the file name .war and select destination paths and after that
we will get the .war file.

- 32 -
Core Java
************************** JSP Questions : ************************

What is a JSP? What is it used for? What do you understand by the term JSP translation phase or
compilation phase?
Ans) JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used as the
presentation layer for combining HTML and Java code. While Java Servlet technology is capable of generating
HTML with out.println(“….. ”) statements, where out is a PrintWriter. This process of embedding HTML code
with escape characters is cumbersome and hard to maintain. The JSP technology solves this by providing a
level of abstraction so that the developer can use custom tags and action elements, which can speed up Web
development and are easier to maintain.

The JSPs have a translation or a compilation process where the JSP engine translates and compiles a JSP file
into a JSP Servlet. The translated and compiled JSP Servlet moves to the execution phase (run time) where
they can handle requests and send response.

Unless explicitly compiled ahead of time, JSP files are compiled the first time they are accessed. On large
production sites, or in situations involving complicated JSP files, compilation may cause unacceptable delays to
users first accessing the JSP page. The JSPs can be compiled ahead of time (ie precompiled) using application
server tools/settings or by writing your own script.
Explain the life cycle methods of a JSP?
Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
Translated: The JSP file has been translated and compiled as a Servlet.
Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize
the Servlet. Called only once per Servlet instance.
Servicing: Services the client requests. Container calls this method for each request.
Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.
What are different type of scripting elements?
Ans)
Declaration Element: is the embedded Java declaration statement, which gets inserted at the Servlet class
level.
<%! Calendar c = Calendar.getInstance(); %>

Important: declaring variables via this element is not thread-safe, because this variable ends up in the
generated Servlet as an instance variable, not within the body of the _jspservice() method. Ensure their
access is either read-only or synchronized.
Expression Element: is the embedded Java expression, which gets evaluated by the service method.
<%= new Date()>
Scriptlet Elements: are the embedded Java statements, which get executed as part of the service method.
(Note: Not recommended to use Scriptlet elements because they don’t provide reusability and maintainability.
Use custom tags (like JSTL, JSF tags, etc) or beans instead).
<%
//Java codes
String userName=null;
userName=request.getParameter("userName");
%>

Action Elements: A JSP element that provides information for execution phase.
<jsp:useBean id="object_name" class="class_name"/>
<jsp:include page="scripts/login.jsp" />

Directive Elements: A JSP element that provides global information for the translation phase.
<%@ page import=”java.util.Date” %>
<%@ include file=”myJSP” %>
<%@ taglib uri=”tagliburi” prefix=”myTag”%>
Q4) What are the different scope values or what are the different scope values for ?
Ans)
Scope Object Comment
Page PageContext Available to the handling JSP page only.
Request Request Available to the handling JSP page or Servlet and
forwarded JSP page or Servlet.
Session Session Available to any JSP Page or Servlet within the

- 33 -
Core Java
same session.
Application Application Available to all the JSP pages and Servlets within
the same Web Application.
Q5) What are the differences between static and a dynamic include?

Ans)
Static <%@include%> Dynamic include <include....>
During the translation or compilation phase all The dynamically included JSP is compiled into a
the included JSP pages are compiled into a separate Servlet. It is a separate resource, which
single Servlet. gets to process the request, and the content
generated by this resource is included in the JSP
response.
No run time performance overhead. Has run time performance overhead.

Q6) Is JSP variable declaration thread safe?


Ans) No. The declaration of variables in JSP is not thread-safe, because the declared variables end up in the
generated Servlet as an instance variable, not within the body of the _jspservice() method.
The following declaration is not thread safe: because these are declarations, and will only be evaluated once
when the page is loaded
<%! int a = 5 %>
The following declaration is thread safe: because the variables declared inside the scriplets have the local
scope and not shared.
<% int a = 5 %>;
Q7) Explain JSP URL mapping? What is URL hiding or protecting the JSP page?
Ans) The JSP resources usually reside directly or under subdirectories (e.g. myPath) of the document root,
which are directly accessible to the user through the URL. If you want to protect your Web resources then
hiding the JSP files behind the WEB-INF directory can protect the JSP files, css (cascading style sheets) files,
Java Script files, pdf files, image files, html files etc from direct access. The request should be made to a
servlet who is responsible for authenticating and authorising the user before returning the protected JSP page
or its resources.
Q8) What are custom tags? Explain how to build custom tags?
Ans) Custom JSP tag is a tag you define. You define how a tag, its attributes and its body are interpreted,
and then group your tags into collections called tag libraries that can be used in any number of JSP files. So
basically it is a reusable and extensible JSP only solution. The pre-built tags also can speed up Web
development.
Step 1
Create a Custom tag class using only doStartTag()
package myTagPkg;
public class MyTag extends TagSupport
{
int attr = null;
public int setAttr(int a ttr){
this.attr = a ttr
}
public int getAttr(){
return attr;
}
public int doStartTag() throws JspException {
.......
return 0;
}
public void release(){.....}
}

Step 2 The Tag library descriptor file (*.tld) maps the XML element names to the tag implementations. The
code sample MyTagDesc.tld is shown below:
<taglib>
<tag>
<name>tag1</name>
<tagclass>myTagPkg.MyTag</tagclass>
<bodycontent>empty</bodycontent>
- 34 -
Core Java
<attribute>
<name>attr</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
Step 3
The web.xml deployment descriptor maps the URI to the location of the *.tld (Tag Library Descriptor) file. The
code sample web.xml file is shown below:
<web-app>
<taglib>
<taglib-uri>/WEB-INF/MyTagURI</taglib-uri>
<taglib-location>/WEB-INF/tags/MyTagDesc.tld</taglib-location>
</taglib>
</web-app>
STEP: 4 The JSP file declares and then uses the tag library as shown below:
<%@ taglib uri="/WEB-INF/ MyTagURI" prefix="myTag" %>
< myTag:tag1 attr=”abc” />
<taglib>
<tag>
<name>tag1</name>
<tagclass>myTagPkg.MyTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>attr</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
Q9) What is the difference between custom JSP tags and JavaBeans?

Ans) In the context of a JSP page, both accomplish similar goals but the differences are:
Custom Tags JavaBeans
Can manipulate JSP content. Can’t manipulate JSP content.
Custom tags can simplify the complex operations
much better than the bean can. But require a bit more Easier to set up.
work to set up.
Can be used in both Servlets and JSPs. You can define a
Used only in JSPs in a relatively self-contained
bean in one Servlet and use them in another Servlet or
manner.
a JSP page.

JavaBeans declaration and usage example:


<jsp:useBean id="identifier" class="packageName.className"/>
<jsp:setProperty name="identifier" property="classField" value="someValue" />
<jsp:getProperty name="identifier" property="classField" />
<%=identifier.getclassField() %>
What is a Expression?
A: An expression tag contains a scripting language expression that is evaluated, converted to a String, and
inserted where the expression appears in the JSP file. Because the value of an expression is converted to a
String, you can use an expression within text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression.
Q11) Difference between forward and sendRedirect?
Ans) When you invoke a forward request, the request is sent to another resource on the server, without the
client being informed that a different resource is going to process the request. This process occurs completly
with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to
the browser indicating that a new URL should be requested. Because the browser issues a completly new

- 35 -
Core Java
request any object that are stored as request attributes before the redirect occurs will be lost. This extra
round trip a redirect is slower than forward.

Q12) What are implicit objects? List them?


Ans) Certain objects that are available for the use in JSP documents without being eclared first. These objects
are parsed by the JSP engine and inserted into the generated servlet. The implicit objects are listed below:
request
response
pageContext
session
application
out
config
page
exception

Q13) How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

Ans) You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by
the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your
JSP pages to prevent them from being cached at the browser. You need both the statements to take care of
some of the older browser versions.

<% response.setHeader("Cache-Control","no-store"); //HTTP 1.1


response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

Q14) How to implement a thread-safe JSP page? What are the advantages and Disadvantages of
using it?

Ans) JSPs can be thread-safe by having them implement the SingleThreadModel interface. This is done by
adding the directive
<%@ page isThreadSafe="false" %>

within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded
in memory, you will have N instances of the servlet loaded and initialized, with the service method of each
instance effectively synchronized. You can typically control the number of instances (N) that are instantiated
for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More
importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true,
as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race
condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the
example above of not being able to use . You should try really hard to make them thread-safe the old
fashioned way: by making them thread-safe .

Q15) Why to use the HttpServlet Init method to perform expensive operations that need only be
done once?

Ans) Because the servlet init() method is invoked when servlet instance is loaded, it is the perfect location to
carry out expensive operations that need only be performed during initialization. By definition, the init()
method is thread-safe. The results of operations in the HttpServlet.init() method can be cached safely in
servlet instance variables, which become read-only in the servlet service method.

Q16) Why is it not a good practice to create HttpSessions in JSPs by default?


Ans) By default, JSP files create HttpSessions. This is in compliance with J2EETM to facilitate the use of JSP
implicit objects, which can be referenced in JSP source and tags without explicit declaration. HttpSession is
one of those objects. If you do not use HttpSession in your JSP files then you can save some performance
overhead with the following JSP page directive:
<%@ page session="false"%>

- 36 -
Core Java
Q17) What are the standard actions available in JSP?

Ans) The standard actions available in JSP are as follows:


<jsp:include>: It includes a response from a servlet or a JSP page into the current page. It differs from an
include directive in that it includes a resource at request processing time, whereas the include directive
includes a resource at translation time.
<jsp:forward>: It forwards a response from a servlet or a JSP page to another page.
<jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean.
<jsp:setProperty>: It sets the properties for a JavaBean.
<jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to the response.
<jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a
request. These parameters are provided using the name-value pairs.
<jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.

OOPS Concept
Q1) What is polymorphism?
Ans) Polymorphism gives us the ultimate flexibility in extensibility. The abiltiy to define more than pne
function with the same name is called Polymorphism. In java,c++ there are two type of polymorphism:
compile time polymorphism (overloading) and runtime polymorphism (overriding).

When you override methods, JVM determines the proper methods to call at the program’s run time, not at the
compile time. Overriding occurs when a class method has the same name and signature as a method in parent
class.

Overloading occurs when several methods have same names with

Overloading is determined at the compile time.

Different method signature and different number or type of parameters.


Same method signature but different number of parameters.
Same method signature and same number of parameters but of different type

int add(int a,int b)


float add(float a,int b)
float add(int a ,float b)
void add(float a)
int add(int a)
void add(int a) //error conflict with the method int add(int a)

Example: Overloading
Class BookDetails{
String title;
String publisher;
float price;
setBook(String title){
}
setBook(String title, String publisher){
}
setBook(String title, String publisher,float price){
}
}

Example: Overriding
class BookDetails{
String title;
setBook(String title){ }
}
class ScienceBook{
- 37 -
Core Java
setBook(String title){} //overriding
setBook(String title, String publisher,float price){ } //overloading
}

Q2) What is inheritance?


Ans) Inheritance is the property which allows a Child class to inherit some properties from its parent class. In
Java this is achieved by using extends keyword. Only properties with access modifier public and protected can
be accessed in child class.
public class Parent{
public String parentName;
public int parentage;
public String familyName;
}
public class Child extends Parent{
public String childName;
public int childAge;
public void printMyName(){
System.out.println(“ My name is “+ chidName+” “ +familyName)
}
}
In above example the child has inherit its family name from the parent class just by inheriting the class.
Q3) What is multiple inheritance and does java support?
Ans) If a child class inherits the property from multiple classes is known as multiple inheritance.
Java does not allow to extend multiple classes but to overcome this problem it allows to implement multiple
Interfaces.
Q4) What is abstraction?
Ans) Abstraction is way of converting real world objects in terms of class. For example creating a class Vehicle
and injecting properties into it. E.g
public class Vehicle {
public String colour;
public String model;
}
Q5) What is data hiding?
Ans) The way of providing restriction to the access of property of a class is called data hiding. In java this is
achieved by using access modifiers: - public, private, protected and default.
Q6) What is encapsulation?
Ans) The combination of abstraction and data hiding for a class is called encapsulation.

********************* Key Concepts in Java ************************************


Q1) Why is main() method static?
Ans) To access the static method the object of the class is not needed. The method can be access directly with
the help of ClassName. So when a program is started the jvm search for the class with main method and calls
it without creating an object of the class.
Q2) What is the difference between static methods and instance methods?
Ans) instance method belongs to the instance of a class therefore it requires an instance before it can be
invoked, whereas static method belongs to the class itself and not to any class instance so it doesn’t need an
instance to be invoked.
Instance methods use dynamic (late) binding, whereas static methods use static (early) binding.
When the JVM invokes a class instance method, it selects the method to invoke based on the type of the
object reference, which is always known at run-time. On the other hand, when the JVM invokes a static
method, it selects the method to invoke based on the actual class of the object, which may only be known at
compile time.

Q3) Can static block throw exception?


Ans) Yes, static block can throw only Runtime exception or can use a try-catch block to catch checked
exception.
Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught,
logged and application can exit. If System.exit() is not done, then application may continue and next time if
the class is referred JVM will throw NoClassDefFounderror since the class was not loaded by the Classloader.

Q4 What is difference between abstract class and interface?

- 38 -
Core Java
Ans)
1) A class is called abstract when it contains at least one abstract method. It can also contain n numbers of
concrete method.Interface can contain only abstract( non implemented) methods.
2) The abstract class can have public,private,protect or default variables and also constants. In interface the
variable is by default public final. In nutshell the interface doesnt have any variables it only has constants.
3) A class can extend only one abstract class but a class can implement multiple interfaces.
4) If an interface is implemented its compulsory to implement all of its methods but if an abstract class is
extended its not compulsory to implement all methods. 5) The problem with an interface is, if you want to add
a new feature (method) in its contract, then you MUST implement those method 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.
Q5) Explain with example to describe when to use abstract class and interface?
Ans) Consider a scenario where all Cars will have 4 tyres and other features can be different.
In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will be used and a
default implementaion for tyres will be provided.
public abstract class Car{
public abstract String getCarName();
public final int getNoOfTyres(){
return 4;
}
}

Consider a scenario where Cars can have any number of tyres and other features can also be different. In this
case interface will be created.
public interface Car{
public abstract String getCarName();
public abstract int getNoOfTyres();
}

Q6) Does java support multiple interitance? Why?

Ans) Java doesnt support multiple inheritance but it provide a way through which it can enact it.
Consider the scenario is C++
Class A{
public void add(){
// some text
}
}

Class B{
public void add(){
// some text
}
}

Class C extends A,B{


public static void main(String arg[]){
C objC = new C();
objC.add(); // problem, compiler gets confused and cant
decide to call Class A or B method.
}
This problem is called Diamond problem.
This problem in java is taken care with the use of interfaces
In Java similar problem would look like:
interface A{
add();
}
interface B{
add();
}
class C implements A,B{
add(){
// doesnt matter which interface it belong to
- 39 -
Core Java
}
}

Q7) Can this keyword be assigned null value?


Ans) No
Q8) What are the different types of references in java?
Ans) Java has a more expressive system of reference than most other garbage-collected programming
languages, which allows for special behavior for garbage collection. A normal reference in Java is known as a
strong reference. The java.lang.ref package defines three other types of references—soft, weak, and phantom
references. Each type of reference is designed for a specific use.

A SoftReference can be used to implement a cache. An object that is not reachable by a strong reference (that
is, not strongly reachable), but is referenced by a soft reference is called softly reachable. A softly reachable
object may be garbage collected at the discretion of the garbage collector. This generally means that softly
reachable objects will only be garbage collected when free memory is low, but again, it is at the discretion of
the garbage collector. Semantically, a soft reference means "keep this object unless the memory is needed."

A WeakReference is used to implement weak maps. An object that is not strongly or softly reachable, but is
referenced by a weak reference is called weakly reachable. A weakly reachable object will be garbage
collected during the next collection cycle. This behavior is used in the class java.util.WeakHashMap. A weak
map allows the programmer to put key/value pairs in the map and not worry about the objects taking up
memory when the key is no longer reachable anywhere else. Another possible application of weak references
is the string intern pool. Semantically, a weak reference means "get rid of this object when nothing else
references it."

A PhantomReference is used to reference objects that have been marked for garbage collection and have been
finalized, but have not yet been reclaimed. An object that is not strongly, softly or weakly reachable, but is
referenced by a phantom reference is called phantom reachable. This allows for more flexible cleanup than is
possible with the finalization mechanism alone. Semantically, a phantom reference means "this object is no
longer needed and has been finalized in preparation for being collected."

Q9) How to change the heap size of a JVM?


Ans) The old generation's default heap size can be overridden by using the -Xms and -Xmx switches to
specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program

Q10) What is difference between instanceof and isInstance(Object obj)?


Ans) Differences are as follows:

instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class.


instanceof method is used to check the type of an object which are known at compile time and isInstance()
could only be called on class, San instance of java.lang.Class.
if (obj instanceof MyType) {
...
}else if (MyType.class.isInstance(obj)) {
...
}

instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj)
is used to identify object of a particular class.

Q11) Java supports pass by value or pass by reference?


Ans) Java supports only pass by value. The arguments passed as a parameter to a method is mainly primitive
data types or objects. For the data type the actual value is passed.
Java passes the references by value just like any other parameter. This means the references passed to the
method are actually copies of the original references.Java copies and passes the reference by value, not the
object. Thus, method manipulation will alter the objects, since the references point to the original
objects.Consider the example:
public void tricky(Point arg1, Point arg2)
{
- 40 -
Core Java
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}

OutPut:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1
and pnt2 fails! This is the major source of confusion. In the main() method, pnt1 and pnt2 are nothing more
than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by
value just like any other parameter. This means the references passed to the method are actually copies of
the original references.

Q12) What is memory leak?


Ans) A memory leak is where an unreferenced object that will never be used again still hangs around in
memory and doesnt get garbage collected.

Q13) What is the difference between equals() and ==?

Ans) == operator is used to compare the references of the objects.


public bollean equals(Object o) is the method provided by the Object class. The default implementation uses
== operator to compare two objects.
But since the method can be overriden like for String class. equals() method can be used to compare the
values of two objects.

String str1 = "MyName";


String str2 = "MyName";
String str3 = str2;

if(str1 == str2){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}

if(str1.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}

Output:
Objects are not equal
Objects are equal
String str2 = "MyName";
String str3 = str2;
if(str2 == str3){
- 41 -
Core Java
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}

if(str3.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}

OutPut:
Objects are equal
Objects are equal

Q14) How to make sure that Childclass method actually overrides the method of the superclass?
Ans) The @Override annotation can be added to the javadoc for the new method. If you accidently miss an
argument or capitalize the method name wrong, the compiler will generate a compile-time error.

Q15) How to find the size of an object?


Ans)The heap size of an object can be found using -
Runtime.totalMemory()-Runtime.freeMemory() .
Q16) Can an abstract class have a static method?
Ans) Yes an abstract class have a static method and it can be accessed by any other class(even not a concrete
class).
Q17) Can an abstract class have a constructor?
Ans) Yes an abstract class have a default and parameterized constructors.
Q18) Why static methods cannot access non static variables or methods?
Ans) A static method cannot access non static variables or methods because static methods doesnt need the
object to be accessed. So if a static method has non static variables or non static methods which has
instantiated variables they will no be intialized since the object is not created and this could result in an error.

Q19) What is difference between stringbuffer and stringbuilder?


Ans) The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized
whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it
is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Criteria to choose among StringBuffer and StringBuilder

1)If your text can change and will only be accessed from a single thread, use a StringBuilder 2)because
StringBuilder is unsynchronized.

If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer
is synchronous.

Q20) Consider a scenario in which the admin want to sure that if some one has written
System.exit() at some part of application then before system shutdown all the resources should be
released. How is it possible?
Ans) This is possible using Runtime.getRuntime().addShutdownHook(Thread hook).
Straight from Java Spec:
This method registers a new virtual-machine shutdown hook.
The Java virtual machine shuts down in response to two kinds of events:
1. The program exits normally, when the last non-daemon thread exits or when the exit (equivalently,
System.exit) method is invoked, or
2. The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide
event, such as user logoff or system shutdown.

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown
sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.
When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been
enabled. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the
shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method.

- 42 -
Core Java
Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly
terminates the virtual machine.
Q21) What is the difference between final, finally and finalize() in Java?
Ans)
final - constant declaration. A final variable act as constant, a final class is immutable and a final method
cannot be ovrriden.
finally - handles exception. The finally block is optional and provides a mechanism to clean up regardless of
what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release
other system resources like database connections, statements etc.
finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the
garbage collector, allowing it to clean up its state. Should not be used to release non-memory resources like
file handles, sockets, database connections etc because Java has only a finite number of these resources and
you do not know when the garbage collection is going to kick in to release these non-memory resources
through the finalize() method.
Q22) How does Java allocate stack and heap memory?
Ans) Each time an object is created in Java it goes into the area of memory known as heap. The primitive
variables like int and double are allocated in the stack, if they are local method variables and in the heap if
they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack when
a method is invoked and stack pointer is decremented when a method call is completed.
In a multi-threaded application each thread will have its own stack but will share the same heap. This is why
care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is
threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with
synchronisation through your code.
Q23) Explain re-entrant, recursive and idempotent methods/functions?
Ans) A method in stack is re-entrant allowing multiple concurrent invocations that do not interfere with each
other.
A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in
Java though it is tough to debug. Recursive functions are useful in removing iterations from many sorts of
algorithms. Allrecursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent
methods are methods, which are written in such a way that repeated calls to the same method with the same
arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can
automatically recover from a server failure as long as it can reach another server.
Q24)Can a private variable or method of a class can be accessed?
Ans) Yes its possible using reflection.
Q25)What is difference between static block and the init block?
Or
Difference between
Static {} and {}
Ans) The static block is loaded when the class is loaded by the JVM for the 1st time only whereas init {} block
is loaded every time class is loaded. Also first the static block is loaded then the init block.
public class LoadingBlocks {
static{
System.out.println("Inside static");
}
{
System.out.println("Inside init");
}
public static void main(String args[]){
new LoadingBlocks();
new LoadingBlocks();
new LoadingBlocks();
}
}
Output:
Inside static
Inside init
Inside init
Inside init

Q26)Why inner class can access only final variable?


Ans) Local classes can most definitely reference instance variables. The reason they cannot reference non
final local variables is because the local class instance can remain in memory after the method returns. When
the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't
- 43 -
Core Java
final then the copy of the variable in the method could change, while the copy in the local class didn't, so
they'd be out of synch.
Anonymous inner classes require final variables because of the way they are implemented in Java. An
anonymous inner class (AIC) uses local variables by creating a private instance field which holds a copy of the
value of the local variable. The inner class isn't actually using the local variable, but a copy. It should be fairly
obvious at this point that a "Bad Thing"™ can happen if either the original value or the copied value changes;
there will be some unexpected data synchronization problems. In order to prevent this kind of problem, Java
requires you to mark local variables that will be used by the AIC as final (i.e., unchangeable). This guarantees
that the inner class' copies of local variables will always match the actual values.
Q27)What is fully abstract class?
Ans) An abstract class which has all methods as abstract and all fields are public static final.
Q28)What is dynamic binding and static binding?
Ans) Method invocation
The Java programming language provides two basic kinds of methods: instance methods and class (or static)
methods. The difference are:
1. Instance methods require an instance before they can be invoked, whereas class methods do not.
2. Instance methods use dynamic (late) binding, whereas class methods use static (early) binding.
When the Java virtual machine invokes a class method, it selects the method to invoke based on the type of
the object reference, which is always known at compile-time. On the other hand, when the virtual machine
invokes an instance method, it selects the method to invoke based on the actual class of the object, which
may only be known at run time.
Q29) What is Java Reflection?
Ans)Reflection is commonly used by programs which require the ability to examine or modify the runtime
behavior of applications running in the Java virtual machine.
Drawbacks of Reflection: Reflection is powerful, but should not be used indiscriminately. If it is possible to
perform an operation without using reflection, then it is preferable to avoid using it. The following concerns
should be kept in mind when accessing code via reflection.
Performance Overhead: Because reflection involves types that are dynamically resolved, certain Java virtual
machine optimizations can not be performed. Consequently, reflective operations have slower performance
than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in
performance-sensitive applications.
Security Restrictions: Reflection requires a runtime permission which may not be present when running under
a security manager. This is in an important consideration for code which has to run in a restricted security
context, such as in an Applet.
Exposure of Internals: Since reflection allows code to perform operations that would be illegal in non-reflective
code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects,
which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and
therefore may change behavior with upgrades of the platform.
Q30) When an obj is passed through a function , u can set the properties but u cannot set a new
memory location?
Ans) It is because when u pass an object the address value is passed and stored in some new address . like if
address 1234 is passed , it is stored in 4567 location. So if u change in the value of an object it will take the
address from 4567 and do 1234.setXXX(). If u set the object to null it will set 4567=null.

Collections Interview Questions


Q1) What is difference between ArrayList and vector?
Ans: )
1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method
like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.

2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an
element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out
of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50
percent.
Q2) How can Arraylist be synchronized without using Vector?
Ans) Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)
Q3) If an Employee class is present and its objects are added in an arrayList. Now I want the list to
be sorted on the basis of the employeeID of Employee class. What are the steps?

- 44 -
Core Java
Ans) 1) Implement Comparable interface for the Employee class and override the compareTo(Object obj)
method in which compare the employeeID
2) Now call Collections.sort() method and pass list as an argument.
Now consider that Employee class is a jar file.
1) Since Comparable interface cannot be implemented, create Comparator and override the compare(Object
obj, Object obj1) method .
2) Call Collections.sort() on the list and pass comparator as an argument.
Q4)What is difference between HashMap and HashTable?
Ans) Both collections implements Map. Both collections store value as key-value pairs. The key differences
between the two are
1. Hashmap is not synchronized in nature but hshtable is.
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Fail-safe - “if the Hashtable is structurally modified at any time after the iterator is created, in any way except
through the iterator's own remove method, the iterator will throw a ConcurrentModificationException”
3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or value as null.
Q5) What are the classes implementing List interface?
Ans)
There are three classes that implement List interface:
1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically
also operations like add,remove and get can be formed once the object is created. It also ensures that the
data is retrieved in the manner it was stored. The ArrayList is not thread-safe.
2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized
block.

3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation
for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle
of a list.
Q6) Which all classes implement Set interface?
Ans) A Set is a collection that contains no duplicate elements. More formally, sets contain no pair of elements
e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the
commnly used class which implements Set interface.
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be
iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements
inserted into the interface must implement Comparable or Comparator interface.
TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n)
time cost for the basic operations (add, remove and contains). The class is not synchronized.
HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It
makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order
will remain constant over time. This class permits the null element. This class offers constant time
performance for the basic operations (add, remove, contains and size), assuming the hash function disperses
the elements properly among the buckets
Q7) What is difference between List and a Set?
Ans)
1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements.
2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the
sequence in which data can be retrieved.(Except HashSet)
Q8) What is difference between Arrays and ArrayList ?
Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared
as :
int [] intArray= new int[6];
intArray[7] // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
Once the array is created elements cannot be added or deleted from it. But with ArrayList the elements can be
added and deleted at runtime.
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
ArrayList is one dimensional but array can be multidimensional.
int[][][] intArray= new int[3][2][1]; // 3 dimensional array

To create an array the size should be known or initalized to some value. If not initialized carefully there could
me memory wastage. But arrayList is all about dynamic creation and there is no wastage of memory.
- 45 -
Core Java
Q9) When to use ArrayList or LinkedList ?
Ans) Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using
"get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of
a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the
underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is
fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases
where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in
the middle of the list.
Q10) Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible
ways and which is the fastest?
Ans) It can be done in two ways, using for loop or using iterator of ArrayList. The first option is faster than
using iterator. Because value stored in arraylist is indexed access. So while accessing the value is accessed
directly as per the index.
Q11) Now another question with respect to above question is if accessing through iterator is slow
then why do we need it and when to use it.
Ans) For loop does not allow the updation in the array(add or remove operation) inside the loop whereas
Iterator does. Also Iterator can be used where there is no clue what type of collections will be used because all
collections have iterator.
Q12) Which design pattern Iterator follows?
Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The Iterator pattern is
one, which allows you to navigate through a collection of data using a common interface without knowing
about the underlying implementation. Iterator should be implemented as an interface. This allows the user to
implement it anyway its easier for him/her to return data. The benefits of Iterator are about their strength to
provide a common interface for iterating through collections without bothering about underlying
implementation.

Example of Iteration design pattern - Enumeration The class java.util.Enumeration is an example of the
Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential
order without the client having to know the representation of the collection being iterated over. It can be used
to provide a uniform interface for traversing collections of all kinds.

Q13) Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of


ArrayList<String> = new ArrayList<String>();
Ans) It is preferred because:
If later on code needs to be changed from ArrayList to Vector then only at the declaration place we can do
that.
The most important one – If a function is declared such that it takes list. E.g void showDetails(List list);
When the parameter is declared as List to the function it can be called by passing any subclass of List like
ArrayList,Vector,LinkedList making the function more flexible

Q14) What is difference between iterator access and index access?


Ans) Index based access allow access of the element directly on the basis of index. The cursor of the
datastructure can directly goto the 'n' location and get the element. It doesnot traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to
reach the 'n'th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are performed on
elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are performed on
elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.

ArrayList is index access and LinkedList is iterator access.


Q15) How to sort list in reverse order?
Ans) To sort the elements of the List in the reverse natural order of the strings, get a reverse Comparator
from the Collections class with reverseOrder(). Then, pass the reverse Comparator to the sort() method.
List list = new ArrayList();
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp)
Q16) Can a null element added to a Treeset or HashSet?
Ans) A null element can be added only if the set contains one element because when a second element is
added then as per set defination a check is made to check duplicate value and comparison with null element
will throw NullPointerException.
HashSet is based on hashMap and can contain null element.
- 46 -
Core Java
Q17) How to sort list of strings - case insensitive?
Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Q18) How to make a List (ArrayList,Vector,LinkedList) read only?
Ans) A list implemenation can be made read only using Collections.unmodifiableList(list). This method returns
a new list. If a user tries to perform add operation on the new list; UnSupportedOperationException is thrown.
Q19) What is ConcurrentHashMap?
Ans) A concurrentHashMap is thread-safe implementation of Map interface. In this class put and remove
method are synchronized but not get method. This class is different from Hashtable in terms of locking; it
means that hashtable use object level lock but this class uses bucket level lock thus having better
performance.
Q20) Which is faster to iterate LinkedHashSet or LinkedList?
Ans) LinkedList.
Q21) Which data structure HashSet implements
Ans) HashSet implements hashmap internally to store the data. The data passed to hashset is stored as key
in hashmap with null as value.
Q22) Arrange in the order of speed - HashMap,HashTable,
Collections.synchronizedMap,concurrentHashmap
Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.
Q23) What is identityHashMap?
Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be used for both
performance reasons, if you know that two different elements will never be equals and for preventing
spoofing, where an object tries to imitate another.
Q24) What is WeakHashMap?
Ans) A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically
be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given
key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized,
and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this
class behaves somewhat differently than other Map implementations.

Exceptions Questions
Q1) What is an Exception?
Ans) The exception is said to be thrown whenever an exceptional event occurs in java which signals that
something is not correct with the code written and may give unexpected result. An exceptional event is a
occurrence of condition which alters the normal program flow. Exceptional handler is the code that does
something about the exception.
Q2) Exceptions are defined in which java package?
Ans)All the exceptions are subclasses of java.lang.Exception
Q3) How are the exceptions handled in java?
Ans)When an exception occurs the execution of the program is transferred to an appropriate exception
handler.The try-catch-finally block is used to handle the exception.
The code in which the exception may occur is enclosed in a try block, also called as a guarded region.
The catch clause matches a specific exception to a block of code which handles that exception.
And the clean up code which needs to be executed no matter the exception occurs or not is put inside the
finally block
Q4) Explain the exception hierarchy in java.
Ans) The hierarchy is as follows:
Throwable is a parent class off all Exception classes. They are two types of Exceptions: Checked exceptions
and UncheckedExceptions. Both type of exceptions extends Exception class.
Q5) What is Runtime Exception or unchecked exception?
Ans) Runtime exceptions represent problems that are the result of a programming problem. Such problems
include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object
through a null reference; and indexing exceptions, such as attempting to access an array element through an
index that is too large or too small. Runtime exceptions need not be explicitly caught in try catch block as it
can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime
exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require
that you catch or specify runtime exceptions (although you can). The solution to rectify is to correct the
programming logic where the exception has occurred or provide a check.
Q6) What is checked exception?
Ans) Checked exception are the exceptions which forces the programmer to catch them explicitly in try-catch
block. It is a subClass of Exception. Example: IOException.
Q7) What is difference between Error and Exception?

- 47 -
Core Java
Ans) An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM
errors and you can not repair them at runtime.Though error can be caught in catch block but the execution of
application will come to a halt and is not recoverable.
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.)
Q8) What is difference between ClassNotFoundException and NoClassDefFoundError?
Ans) A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the
CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was
loaded in a parent classloader and hence the class from the child classloader is not visible.
Consider if NoClassDefFoundError occurs which is something like
java.lang.NoClassDefFoundError
src/com/TestClass
does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found
by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This
typically happens when the class in question has static blocks or members which use a Class that's not found
by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and
look for code using static blocks or static members.
Q9) What is throw keyword?
Ans) Throw keyword is used to throw the exception manually. It is mainly used when the program fails to
satisfy the given condition and it wants to warn the application.The exception thrown should be subclass of
Throwable.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}
public void child{
String iAmMandatory=null;
if(iAmMandatory == null){
throw (new MyCustomException("Throwing exception using throw keyword");
}
}
Q10) What is use of throws keyword?
Ans) If the function is not capable of handling the exception then it can ask the calling method to handle it by
simply putting the throws clause at the function declaration.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}
public void child throws MyCustomException{
//put some logic so that the exception occurs.
}
Q11) What are the possible combination to write try, catch finally block?
Ans)
1) try{
//lines of code that may throw an exception
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}finally{
//the clean code which is executed always no matter the exception occurs or not.
}
2 try{
}finally{}
3 try{
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}
The catch blocks must always follow the try block. If there are more than one catch blocks they all must follow
each other without any block in between. The finally block must follow the catch block if one is present or if
the catch block is absent the finally block must follow the try block.
- 48 -
Core Java
Q12) How to create custom Exception?
Ans) To create you own exception extend the Exception class or any of its subclasses.
e.g.
1 class New1Exception extends Exception { } // this will create Checked Exception
2 class NewException extends IOExcpetion { } // this will create Checked exception
3 class NewException extends NullPonterExcpetion { } // this will create UnChecked exception
Q13) When to make a custom checked Exception or custom unchecked Exception?
Ans) If an application can reasonably be expected to recover from an exception, make it a checked exception.
If an application cannot do anything to recover from the exception, make it an unchecked exception.
Q14)What is StackOverflowError?
Ans) The StackOverFlowError is an Error Object thorwn by the Runtime System when it Encounters that your
application/code has ran out of the memory. It may occur in case of recursive methods or a large amount of
data is fetched from the server and stored in some object. This error is generated by JVM.
e.g. void swap(){
swap();
}
Q15) Why did the designers decide to force a method to specify all uncaught checked exceptions
that can be thrown within its scope?
Ans) Any Exception that can be thrown by a method is part of the method's public programming interface.
Those who call a method must know about the exceptions that a method can throw so that they can decide
what to do about them. These exceptions are as much a part of that method's programming interface as its
parameters and return value.
Q16) Once the control switches to the catch block does it return back to the try block to execute
the balance code?
Ans) No. Once the control jumps to the catch block it never returns to the try block but it goes to finally
block(if present).
Q17) Where is the clean up code like release of resources is put in try-catch-finally block and why?
Ans) The code is put in a finally block because irrespective of try or catch block execution the control will flow
to finally block. Typically finally block contains release of connections, closing of result set etc.
Q18) Is it valid to have a try block without catch or finally?
Ans) NO. This will result in a compilation error. The try block must be followed by a catch or a finally block. It
is legal to omit the either catch or the finally block but not both.
e.g. The following code is illegal.
try{
int i =0;
}
int a = 2;
System.out.println(“a = “+a);
Q19) Is it valid to place some code in between try the catch/finally block that follows it?
Ans) No. There should not be any line of code present between the try and the catch/finally block.
e.g. The following code is wrong.
try{}
String str = “ABC”;
System.out.println(“str = “+str);
catch(Exception e){}
Q20) What happens if the exception is never caught and throws down the method stack?
Ans) If the exception is not caught by any of the method in the method’s stack till you get to the main()
method, the main method throws that exception and the JVM halts its execution.
Q21) How do you get the descriptive information about the Exception occurred during the program
execution?
Ans) All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the
stack trace from where the exception occurred. It prints the most recently entered method first and continues
down, printing the name of each method as it works its way down the call stack from the top.
Q22) Can you catch more than one exceptions in a single catch block?
Ans)Yes. If the exception class specified in the catch clause has subclasses, any exception object that is a
subclass of the specified Exception class will be caught by that single catch block.
E.g..
try {
// Some code here that can throw an IOException
}
catch (IOException e) {
e.printStackTrace();
}
- 49 -
Core Java
The catch block above will catch IOException and all its subclasses e.g. FileNotFoundException etc.
Q23)Why is not considered as a good practice to write a single catchall handler to catch all the
exceptions?
Ans) You can write a single catch block to handle all the exceptions thrown during the program execution as
follows :
try {
// code that can throw exception of any possible type
}catch (Exception e) {
e.printStackTrace();
}
If you use the Superclass Exception in the catch block then you will not get the valuable information about
each of the exception thrown during the execution, though you can find out the class of the exception
occurred. Also it will reduce the readability of the code as the programmer will not understand what is the
exact reason for putting the try-catch block.
Q24) What is exception matching?
Ans) Exception matching is the process by which the the jvm finds out the matching catch block for the
exception thrown from the list of catch blocks. When an exception is thrown, Java will try to find by looking at
the available catch clauses in the top down manner. If it doesn't find one, it will search for a handler for a
supertype of the exception. If it does not find a catch clause that matches a supertype for the exception, then
the exception is propagated down the call stack. This process is called exception matching.
Q25) What happens if the handlers for the most specific exceptions is placed above the more
general exceptions handler?
Ans) Compilation fails. The catch block for handling the most specific exceptions must always be placed above
the catch block written to handle the more general exceptions.
e.g. The code below will not compile.
1 try {
// code that can throw IOException or its subtypes
} catch (IOException e) {
// handles IOExceptions and its subtypes
} catch (FileNotFoundException ex) {
// handle FileNotFoundException only
}
The code below will compile successfully :-
try {
// code that can throw IOException or its subtypes
} catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
} catch (IOException e){
// handle FileNotFoundException only
}
Q26) Does the order of the catch blocks matter if the Exceptions caught by them are not subtype
or supertype of each other
Ans) No. If the exceptions are siblings in the Exception class’s hierarchy i.e. If one Exception class is not a
subtype or supertype of the other, then the order in which their handlers(catch clauses) are placed does not
matter.
Q27) What happens if a method does not throw an checked Exception directly but calls a method
that does? What does 'Ducking' the exception mean?
Ans) If a method does not throw an checked Exception directly but calls a method that throws an exception
then the calling method must handle the throw exception or declare the exception in its throws clause. If the
calling method does not handle and declares the exception, the exceptions is passed to the next method in the
method stack. This is called as ducking the exception down the method stack.
e.g. The code below will not compile as the getCar() method has not declared the CarNotFoundException
which is thrown by the getColor () method.
void getCar() {
getColor();
}
void getColor () {
throw new CarNotFoundException();
}
Fix for the above code is
void getCar() throws CarNotFoundException {
getColor();
}
- 50 -
Core Java
void getColor () {
throw new CarNotFoundException();
}
Q28) Is an empty catch block legal?
Ans) Yes you can leave the catch block without writing any actual code to handle the exception caught.
e.g. The code below is legal but not appropriate, as in this case you will nt get any information about the
exception thrown.
try{
//code that may throw the FileNotFoundException
}catch(FileNotFound eFnf){
//no code to handle the FileNotFound exception
}
Q29)Can a catch block throw the exception caught by itself?
Ans) Yes. This is called rethrowing of the exception by catch block.
e.g. the catch block below catches the FileNotFound exception and rethrows it again.
void checkEx() throws FileNotFoundException {
try{
//code that may throw the FileNotFoundException
}catch(FileNotFound eFnf){
throw FileNotFound();
}
}

Threads Questions
Q1) What is a Thread?
Ans) In Java, "thread" means two different things:
An instance of class java.lang.Thread.
A thread of execution.
An instance of Thread is just…an object. Like any other object in Java, it has variables and methods, and lives
and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its
own call stack. In Java, there is one thread per call stack—or, to think of it in reverse, one call stack per
thread. Even if you don't create any new threads in your program, threads are back there running.
The main() method, that starts the whole ball rolling, runs in one thread, called (surprisingly) the main
thread. If you looked at the main call stack (and you can, any time you get a stack trace from something that
happens after main begins, but not within another thread), you'd see that main() is the first method on the
stack— the method at the bottom. But as soon as you create a new thread, a new stack materializes and
methods called from that thread run in a call stack that's separate from the main() call stack.
Q2) What is difference between thread and process?
Ans) Differences between threads and processes are:-
1. Threads share the address space of the process that created it; processes have their own address.
2. Threads have direct access to the data segment of its process; processes have their own copy of the data
segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use interprocess
communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent process.
6. Threads can exercise considerable control over threads of the same process; processes can only exercise
control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other
threads of the process; changes to the parent process do not affect child processes.
Q3) What are the advantages or usage of threads?
Ans)
Threads support concurrent operations. For example,
• Multiple requests by a client on a server can be handled as an individual client thread.
• Long computations or high-latency disk and network operations can be handled in the background without
disturbing foreground computations or screen updates.
Threads often result in simpler programs.
• In sequential programming, updating multiple displays normally requires a big while-loop that performs
small parts of each display update. Unfortunately, this loop basically simulates an operating system scheduler.
In Java, each view can be assigned a thread to provide continuous updates.
• Programs that need to respond to user-initiated events can set up service routines to handle the events
without having to insert code in the main routine to look for these events.
Threads provide a high degree of control.
- 51 -
Core Java
• Imagine launching a complex computation that occasionally takes longer than is satisfactory. A "watchdog"
thread can be activated that will "kill" the computation if it becomes costly, perhaps in favor of an alternate,
approximate solution. Note that sequential programs must muddy the computation with termination code,
whereas, a Java program can use thread control to non-intrusively supervise any operation.
Threaded applications exploit parallelism.
• A computer with multiple CPUs can literally execute multiple threads on different functional units without
having to simulating multi-tasking ("time sharing").
• On some computers, one CPU handles the display while another handles computations or database accesses,
thus, providing extremely fast user interface response times.
Q4)What are the two ways of creating thread?
Ans) There are two ways to create a new thread.
1)Extend the Thread class and override the run() method in your class. Create an instance of the subclass and
invoke the start() method on it, which will create a new thread of execution. e.g.
public class NewThread extends Thread{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
c.start();
}
}
2)Implements the Runnable interface.The class will have to implement the run() method in the Runnable
interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new
thread of execution will be created. e.g. class
public class NewThread implements Runnable{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}
}
Q5) What are the different states of a thread's lifecycle?
Ans) The different states of threads are as follows:
1) New – When a thread is instantiated it is in New state until the start() method is called on the thread
instance. In this state the thread is not considered to be alive.
2) Runnable – The thread enters into this state after the start method is called in the thread instance. The
thread may enter into the Runnable state from Running state. In this state the thread is considered to be
alive.
3) Running – When the thread scheduler picks up the thread from the Runnable thread’s pool, the thread
starts running and the thread is said to be in Running state.
4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread
switches to this state because of reasons like wait method called or sleep method has been called on the
running thread or thread might be waiting for some i/o resource so blocked. 5) Dead – When the thread
finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state
can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.
Q6) What is use of synchronized keyword?
Ans) synchronized keyword can be applied to static/non-static methods or a block of code. Only one thread at
a time can access synchronized methods and if there are multiple threads trying to access the same method
then other threads have to wait for the execution of method by one thread. Synchronized keyword provides a
lock on the object and thus prevents race condition. E.g.
public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){
synchronized (this){ // synchronized keyword on block of code
}
}
Q7) What is the difference when the synchronized keyword is applied to a static method or to a
non static method?

- 52 -
Core Java
Ans) When a synch non static method is called a lock is obtained on the object. When a synch static method
is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class
don’t interfere with each other. It means, a thread accessing a synch non static method, then the other thread
can access the synch static method at the same time but can’t access the synch non static method.
Q8) What is a volatile keyword?
Ans) In general each thread has its own copy of variable, such that one thread is not concerned with the
value of same variable in the other thread. But sometime this may not be the case. Consider a scenario in
which the count variable is holding the number of times a method is called for a given class irrespective of any
thread calling, in this case irrespective of thread access the count has to be increased so the count variable is
declared as volatile. The copy of volatile variable is stored in the main memory, so every time a thread access
the variable even for reading purpose the local copy is updated each time from the main memory. The volatile
variable also have performance issues.
Q9) What is the difference between yield() and sleep()?
Ans) yield() allows the current the thread to release its lock from the object and scheduler gives the lock of
the object to the other thread with same priority.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it
doesn’t release the lock.
Q10) What is the difference between wait() and sleep()?
Ans)
1) wait() is a method of Object class. sleep() is a method of Object class.
2) sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it
doesn’t release the lock. wait() allows thread to release the lock and goes to suspended state. The thread is
only active when a notify() or notifAll() method is called for the same object.
Q11) What is difference between notify() and notfiyAll()?
Ans) notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first.
Q12) What happens if a start method is not invoked and the run method is directly invoked?
Ans) If a thread has been instantiated but not started its is said to be in new state. Unless until a start()
method is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method
on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked
and the run() method is directly called on the Thread instance, the code inside the run() method will not run
in a separate new thread but it will start running in the existing thread.
Q13) What happens when start() is called?
Ans) A new thread of execution with a new call stack starts. The state of thread changes from new to
runnable. When the thread gets chance to execute its target run() method starts to run.
Q14) If code running is a thread creates a new thread what will be the initial priority of the newly
created thread?
Ans) When a code running in a thread creates a new thread object , the priority of the new thread is set equal
to the priority of the thread which has created it.
Q15) When jvm starts up, which thread will be started up first?
Ans) When jvm starts up the thread executing main method is started.
Q16) What are the daemon threads?
Ans) Daemon thread are service provider threads run in the background,these not used to run the application
code generally.When all user threads(non-daemon threads) complete their execution the jvm exit the
application whatever may be the state of the daemon threads. Jvm does not wait for the daemon threads to
complete their execution if all user threads have completed their execution.
To create Daemon thread set the daemon value of Thread using setDaemon(boolean value) method. By
default all the threads created by user are user thread. To check whether a thread is a Daemon thread or a
user thread use isDaemon() method.
Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused memory by the
application. The Garbage collector code runs in a Daemon thread which terminates as all the user threads are
done with their execution.
Q17) What all constructors are present in the Thread class?
Ans) Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)
Q18) Can the variables or classes be Synchronized?
Ans) No. Only methods can be synchronized.
Q19) How many locks does an object have?
Ans) Each object has only one lock.
Q20) Can a class have both Synchronized and non-synchronized methods?
- 53 -
Core Java
Ans) Yes a class can have both synchronized and non-synchronized methods.
Threads Questions
Q1) If a class has a synchronised method and non-synchronised method, can multiple threads
execute the non-synchronised methods?
Ans) Yes. If a class has a synchronised and non-synchronised methods, multiple threads can access the non-
synchronised methods.
Q2) If a thread goes to sleep does it hold the lock?
Ans) Yes when a thread goes to sleep it does not release the lock.
Q3)Can a thread hold multiple locks at the same time?
Ans) Yes. A thread can hold multiple locks at the same time. Once a thread acquires a lock and enters into
the synchronized method / block, it may call another synchronized method and acquire a lock on another
object.
Q4) Can a thread call multiple synchronized methods on the object of which it hold the lock?
Ans) Yes. Once a thread acquires a lock in some object, it may call any other synchronized method of that
same object using the lock that it already holds.
Q5) Can static methods be synchronized?
Ans) Yes. As static methods are class methods and have only one copy of static data for the class, only one
lock for the entire class is required. Every class in java is represented by java.lang.Class instance. The lock on
this instance is used to synchronize the static methods.
Q6) Can two threads call two different static synchronized methods of the same class?
Ans) No. The static synchronized methods of the same class always block each other as only one lock per
class exists. So no two static synchronized methods can execute at the same time.
Q7)Does a static synchronized method block a non-static synchronized method?
Ans)No As the thread executing the static synchronized method holds a lock on the class and the thread
executing the non-satic synchronized method holds the lock on the object on which the method has been
called, these two locks are different and these threads do not block each other.
Q8) Once a thread has been started can it be started again?
Ans) No. Only a thread can be started only once in its lifetime. If you try starting a thread which has been
already started once an IllegalThreadStateException is thrown, which is a runtime exception. A thread in
runnable state or a dead thread can not be restarted.
Q9) When does deadlock occur and how to avoid it?
Ans) When a locked object tries to access a locked object which is trying to access the first locked object.
When the threads are waiting for each other to release the lock on a particular object, deadlock occurs .
Q10) What is a better way of creating multithreaded application? Extending Thread class or
implementing Runnable?
Ans) If a class is made to extend the thread class to have a multithreaded application then this subclass of
Thread can not extend any other class and the required application will have to be added to this class as it can
not be inherited from any other class. If a class is made to implement Runnable interface, then the class can
extend other class or implement other interface.
Q11) Can the start() method of the Thread class be overridden? If yes should it be overridden?
Ans) Yes the start() method can be overridden. But it should not be overridden as it’s implementation in
thread class has the code to create a new executable thread and is specialised.
Q12) What are the methods of the thread class used to schedule the threads?
Ans) The methods are as follows:
public static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join() throws InterruptedException
public final void setPriority(int priority)
public final void wait() throws InterruptedException
public final void notify()
public final void notifyAll()
Q13) Which thread related methods are available in Object class?
Ans) The methods are:
public final void wait() throws Interrupted exception
public final void notify()
public final void notifyAll()
Q14) Which thread related methods are available in Thread class?
Ans) Methods which are mainly used :
public static void sleep(long millis) throws Interrupted exception
public static void yield() public final void join() throws Interrupted exception
public final void setPriority(int priority)
public void start()
public void interrupt()
- 54 -
Core Java
public final void join()
public void run()
public void resume()
Q15) List the methods which when called the thread does not release the locks held?
Ans) Following are the methods.
notify()
join()
sleep()
yield()
Q16) List the methods which when called on the object the thread releases the locks held on that
object?
Ans) wait()
Q17) Does each thread has its own thread stack?
Ans) Yes each thread has its own call stack. For eg
Thread t1 = new Thread();
Thread t2 = new Thread();
Thread t3 = t1;
In the above example t1 and t3 will have the same stack and t2 will have its own independent stack.
Q18) What is thread starvation?
Ans) In a multi-threaded environment thread starvation occurs if a low priority thread is not able to run or
get a lock on the resoruce because of presence of many high priority threads. This is mainly possible by
setting thread priorities inappropriately.
Q19) What is threadLocal variable?
Ans) ThreadLocal is a class. If a variable is declared as threadLocal then each thread will have a its own copy
of variable and would not interfere with the other's thread copy. Typical scenario to use this would be giving
JDBc connection to each thread so that there is no conflict.
ThreadLocal class by JAVA API
public class ThreadLocal {
public Object get();
public void set(Object newValue);
public Object initialValue();
}
Implementation of ThreadLocal
public class ConnectionDispenser {
private static class ThreadLocalConnection extends ThreadLocal {
public Object initialValue() {
return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
}
}
private static ThreadLocalConnection conn = new ThreadLocalConnection();
public static Connection getConnection() {
return (Connection) conn.get();
}
}

Inner Class Questions


Q1) What is an inner class?
Ans) Inner class is a class defined inside other class and act like a member of the enclosing class.

Q2) What are the different types of inner classes?


Ans) There are two main types of inner classes –
Static member class
Inner class
Member class
Anonymous class
Local class

Q3) What is static member class?


Ans) A static member class behaves much like an ordinary top-level class, except that it can access the static
members of the class that contains it. The static nested class can be accessed as the other static members of
the enclosing class without having an instance of the outer class. The static class can contain non-static and
static members and methods.
public class InnerClass {
- 55 -
Core Java
static class StaticInner {
static int i = 9;
int no = 6;
private void method() {}
public void method1() {}

static void method2() {}


final void method3() {}
}
}

The static inner class can be accessed from Outer Class in the following manner:
InnerClass.StaticInner staticObj= new InnerClass. StaticInner ();

No outer class instance is required to instantiate the nested static class because the static class is a static
member of the enclosing class.

Q4) What are non static inner classes?


Ans)
Non - static inner classes – classes associated with the object of the enclosing class.
Member class - Classes declared outside a function (hence a "member") and not declared "static".
The member class can be declared as public, private, protected, final and abstract. E.g.
public class InnerClass {
class MemberClass {
public void method1() { }
}
}
Method local class – The inner class declared inside the method is called method local inner class. Method local
inner class can only be declared as final or abstract. Method local class can only access global variables or
method local variables if declared as final
public class InnerClass {
int i = 9;
public void method1() {
final int k = 6;
class MethodLocal {
MethodLocal() {
System.out.println(k + i);
}
}
}
}
Anonymous inner class - These are local classes which are automatically declared and instantiated in the
middle of an expression. Also, like local classes, anonymous classes cannot be public, private, protected, or
static. They can specify arguments to the constructor of the superclass, but cannot otherwise have a
constructor. They can implement only one interface or extend a class.
Anonymous class cannot define any static fields, methods, or classes, except for static final constants.
Also, like local classes, anonymous classes cannot be public, private, protected, or static
Some examples:
public class MyFrame extends JFrame {
JButton btn = new JButton();
MyFrame() {
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
}

Anonymous class used with comparator

List<Parent> l = new ArrayList<Parent>();


l.add(new Parent(2));
l.add(new Parent(3));
- 56 -
Core Java
Collections.sort(l, new Comparator() {
public int compare(Object o1, Object o2) {
Parent prt1 = (Parent) o1;
Parent prt2 = (Parent) o2;
if (prt1.getAge() > prt2.getAge()) {
return -1;
}else if(prt1.getAge()<prt2.getAge()) {

return 1;
} else {
return 0;
}
}
});
Q5) Does a static nested class have access to the enclosing class' non-static methods or instance
variables?
Ans) No .
Q6) What are the advantages of Inner classes?
Ans) The embedding of inner class into the outer class in the case when the inner class is to be used only by
one class i.e. the outer class makes the package more streamlined. Nesting the inner class code where it is
used (inside the outer class) makes the code more readable and maintainable.

The inner class shares a special relationship with the outer class i.e. the inner class has access to all members
of the outer class and still have its own type is the main advantages of Inner class. Advantage of inner class is
that they can be hidden from the other classes in the same package and still have the access to all the
members (private also) of the enclosing class. So the outer class members which are going to be used by the
inner class can be made private and the inner class members can be hidden from the classes in the same
package. This increases the level of encapsulation.

If a class A is written requires another class B for its own use, there are two ways to do this. One way is to
write a separate class B or to write an inner class B inside class A. Advantage of writing the inner class B in
the class A is you can avoid having a separate class. Inner classes are best used in the event handling
mechanism and to implement the helper classes. The advantage of using inner class for event handling
mechanism is that the use of if/else to select the component to be handled can be avoided. If inner classes
are used each component gets its own event handler and each event handler implicitly knows the component
it is working for. e.g.

Button btn1 = new Button("Submit");


Btn.addActionListener(new ActionListener(){/br>

Public void actionPerformed(ActionEvent ae){ submitClicked(); }


} );
The advantage of using static nested class is that to instantiate a static nested class you need not create an
instance of the enclosing class which reduces the number of objects the application creates at runtime.
Q7)What are disadvantages of using inner classes?
Ans)
1. Using inner class increases the total number of classes being used by the application. For all the classes
created by JVM and loaded in the memory, jvm has to perform some tasks like creating the object of type
class. Jvm may have to perform some routine tasks for these extra classes created which may result slower
performance if the application is using more number of inner classes.
2. Inner classes get limited support of ide/tools as compared to the top level classes, so working with the
inner classes is sometimes annoying for the developer.
Q8) What are different types of anonymous classes?
Ans 1) Plain old anonymous class type one–
e.g.
class superClass{
void doSomething() {
System.out.println(“Doing something in the Super class”);
}
}

class hasAnonymous{
superClass anon = new superClass(){
- 57 -
Core Java
void doSomething() {
System.out.println(“Doing something in the Anonymous class”);
}
};
Here anon is the reference which is of type superClass which is the class extended by the anonymous class i.e.
superclass of the anonymous class. The method doSomething() is the super class method overridden by the
anonymous class.
2) Plain old anonymous class type two –

interface Eatable{
public void prepareSweets();
}
class serveMeal{
Eatable food = new Eatable(){
public void prepareSweets(){ //come implementation code goes here }
};
}
food is reference variable of type Eatable interface which refers to the anonymous class which is the
implementer of the interface Eatable. The anonymous implementer class of the interface Eatable implements
its method prepareSweets() inside it.
3) Argument defined anonymous class – e.g.

interface Vehicle {
void getNoOfWheels();
}
class Car {
void getType(Vehical v) { }
}
class BeautifulCars {
void getTheBeautifilCar() {
Car c = new Car ();
c.getType (new Vehicle () {
public void getNoOfWheels () {
System.out.println("It has four wheels");
}
});
}
}
Anonymous class is defined as the argument of the method getTheBeautifilCar(), this anonymous class is the
implementer of the interface Vehicle. The method of class Car getTheBeautifilCar() expects the argument as
an object of type Vehicle. So first we create an object of Car referenced by the variable ‘c’. On this object of
Car we call the method getTheBeautifilCar() and in the argument we create an anonymous class in place
which is the implementer of interface Vehicle hence of type Vehicle.
Q9) If you compile a file containing inner class how many .class files are created and what are all
of them accessible in usual way?

Ans) If a inner class enclosed with an outer class is compiled then one .class file for each inner class an a
.class file for the outer class is created. e.g.
class EnclosingOuter {
class Inner{ }
}
If you compile the above code with command
% javac EnclosingOuter.java
Two files
EnclosingOuter.class
EnclosingOuter$Inner.class
will be created. Though a separate inner class file is generated, the inner class file is not accessible in the
usual way like,
% java EnclosingOuter$Inner
Q10) How to access the inner class from code within the outer class?

Ans) The inner class is instantiated only through the outer class instance.
class EnclosingOuter {
- 58 -
Core Java
private int noInnerClass = 1;
public void getNoOfInnerClasses(){
Inner in = new Inner();
System.out.println(“No Of Inner classes is : “+ in.getNoOfClassesFromOuter());
}
class Inner{

public int getNoOfClassesFromOuter(){ return noInnerClass; }

}
Here the method getNoOfInnerClasses() is called on the outer class’s instance through this outer class
instance the inner class instance in is created.
Q11) How to create an inner class instance from outside the outer class instance code?

Ans) To create an instance of the inner class you must have the instance of its enclosing class.
e.g. class EnclosingOuter {
class Inner{ }
}
To create the instance of inner class from class other than the enclosing class.
1) class OtherThanOuter{
EnclosingOuter out = new EnclosingOuter();
EnclosingOuter.Inner in = out.new Inner();
}

2) class OtherThanOuter{
EnclosingOuter.Inner out = new EnclosingOuter.Inner (); }
Q12) How to refer to the outer this i.e. outer class’s current instance from inside the inner class?

Ans) The outer this reference i.e. the outer class’ current instance’ reference can be refered using
‘OuterClassName.this’. E.g
class EnclosingOuter {
class Inner{
System.out.println(“Inner class reference is “ + this); // inner class instance
System.out.println(“Outer class reference is “ + EnclosingOuter.this); //outer class instance
}
}

To reference the inner class reference from within the inner class use this.
Q13) Which modifiers can be applied to the inner class?

Ans) Following are modifiers that can be applied to the inner:


public
private
abstract
final
protected
strictfp
static – turns the inner class into static nested class.
Q14) Can the method local inner class object access method’s local variables?
Ans) No, a method local inner class object can not access the method local variable.
Reason: The local variables are not guaranteed to live as long as the local inner class object. The method local
variable live on stack and exist only till the method lives, their scope is limited only code inside the method
they are declared in. But the local inner class object created within the method lives on heap and it may exist
even after the method ends if in case the reference of this local inner class is passed into some other code and
is stored in an instance variable. So we can not be sure that the local variables will live till the method local
inner class object lives, therefore the method local inner class object can not access the method local variable.
To access the method local variables, the variable has to be declared as final.
Q15) Can a method local inner class access the local final variables?Why?
Ans) Yes. Because the final variables are stored on heap and they live as long as the method local inner class
object may live.
Q16) Which modifiers can be applied to the method local inner class?
Ans) Only abstract or final keyword isallowed.

- 59 -
Core Java
Q17) Can a local class declared inside a static method have access to the instance members of the
outer class?
Ans) No. There is no this reference available in the static method .The static method class can not have
access to any members of the outer class other than static members.
Q18) Can a method which is not in the definition of the superclass of an anonymous class be
invoked on that anonymous class reference?
Ans) No. Compilation will fail.As the reference variable type of the anonymous class will be of superclass
which will not know of any method defined inside the anonymous class the compilation will fail.
e.g. class SuperClass{
void doSomething() {
System.out.println("In the Super class");
}
}
class hasAnonymous{
SuperClass anon = new SuperClass(){
void doSomething() {
System.out.println("In the Anonymous class");
}
void doStuff() {
System.out.println("An Anonymous class method not present in superClass");
}
};

public void doIt(){


anon.doSomething(); // legal superClass has this method
anon.doStuff(); // Not legal }
}
The above code does not compile as the superClass does not know about the anonymous class method
doStuff().
Q19) Can an anonymous class define method of its own?
Ans) Yes. But there will be no way by which the methods defined in the anonymous class which are not
present in its superclass be invoked. As only those methods which are defined in the suprclass which the
anonymous class extends be invoked defining the methods in the anonymous class will be of no use
Q20) Can an anonymous class implement multiple interfaces directly?
Ans) No. An anonymous class can implement only one interface. If the anonymous class is extending a class
then it becomes the implementer of all the interfaces implemented by its superclass automatically.
Q21) Can an anonymous class implement an interface and also extend a class at the same time?
Ans) No. An anonymous class can either extend a class or implement a single interface. If the anonymous
class is extending a class then it becomes the implementer of all the interfaces implemented by its superclass
automatically

Immutable Class Questions


Q1) What is an immutable class?
Ans) Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are
the objects whose state can not be changed once constructed. e.g. String class
Q2) How to create an immutable class?
Ans) To create an immutable class following steps should be followed:
Create a final class.
Set the values of properties using constructor only.
Make the properties of the class final and private
Do not provide any setters for these properties.
If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't provide methods that modify the mutable objects.
Don't share references to the mutable objects. Never store references to external, mutable objects passed to
the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of
your internal mutable objects when necessary to avoid returning the originals in your methods.
E.g.
public final class FinalPersonClass {
private final String name;
private final int age;
public FinalPersonClass(final String name, final int age) {
super();
- 60 -
Core Java
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
Q3) Immutable objects are automatically thread-safe –true/false?
Ans) True. Since the state of the immutable objects can not be changed once they are created they are
automatically synchronized/thread-safe.
Q4) Which classes in java are immutable?
Ans) All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger
Q5) What are the advantages of immutability?
Ans) The advantages are:
1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is
avoided.
2) Once created the state of the immutable object can not be changed so there is no possibility of them
getting into an inconsistent state.
3) The references to the immutable objects can be easily shared or cached without having to copy or clone
them as there state can not be changed ever after construction.
4) The best use of the immutable objects is as the keys of a map.

Cloning questions
Q1) What are different types of cloning in Java?
Ans) Java supports two type of cloning: - Deep and shallow cloning. By default shallow copy is used in Java.
Object class has a method clone() which does shallow cloning.
Q2) What is Shallow copy?
Ans) In shallow copy the object is copied without its contained objects.
Shallow clone only copies the top level structure of the object not the lower levels.
It is an exact bit copy of all the attributes.

Figure 1: Original java object obj


The shallow copy is done for obj and new object obj1 is created but contained objects of obj are not copied.

Figure 2: Shallow copy object obj1


It can be seen that no new objects are created for obj1 and it is referring to the same old contained objects. If
either of the containedObj contain any other object no new reference is created
- 61 -
Core Java
Q3) What is deep copy and how it can be acheived?
Ans) In deep copy the object is copied along with the objects it refers to. Deep clone copies all the levels of
the object from top to the bottom recursively.

Figure 3 : Original Object obj


When a deep copy of the object is done new references are created.

Figure 4: obj2 is deep copy of obj1


One solution is to simply implement your own custom method (e.g., deepCopy()) that returns a deep copy of
an instance of one of your classes. This may be the best solution if you need a complex mixture of deep and
shallow copies for different fields, but has a few significant drawbacks:
 You must be able to modify the class (i.e., have the source code) or implement a subclass. If you have
a third-party class for which you do not have the source and which is marked final, you are out of luck.
 You must be able to access all of the fields of the class’s superclasses. If significant parts of the
object’s state are contained in private fields of a superclass, you will not be able to access them.
 You must have a way to make copies of instances of all of the other kinds of objects that the object
references. This is particularly problematic if the exact classes of referenced objects cannot be known until
runtime.
 Custom deep copy methods are tedious to implement, easy to get wrong, and difficult to maintain.
The method must be revisited any time a change is made to the class or to any of its superclasses.
Other common solution to the deep copy problem is to use Java Object Serialization (JOS). The idea is
simple: Write the object to an array using JOS’s ObjectOutputStream and then use ObjectInputStream to
reconsistute a copy of the object. The result will be a completely distinct object, with completely distinct
referenced objects. JOS takes care of all of the details: superclass fields, following object graphs, and handling
repeated references to the same object within the graph.
 It will only work when the object being copied, as well as all of the other objects references directly or
indirectly by the object, are serializable. (In other words, they must implement java.io.Serializable.)
Fortunately it is often sufficient to simply declare that a given class implements java.io.Serializable and let
Java’s default serialization mechanisms do their thing. Java Object Serialization is slow, and using it to make a
deep copy requires both serializing and deserializing.
There are ways to speed it up (e.g., by pre-computing serial version ids and defining custom readObject() and
writeObject() methods), but this will usually be the primary bottleneck. The byte array stream
implementations included in the java.io package are designed to be general enough to perform reasonable
well for data of different sizes and to be safe to use in a multi-threaded environment. These characteristics,
however, slow down ByteArrayOutputStream and (to a lesser extent) ByteArrayInputStream .
Q4) What is difference between deep and shallow cloning?
Ans) The differences are as follows:
Consider the class:
public class MyData{
String id;
- 62 -
Core Java
Map myData;
}
The shallow copying of this object will have new id object and values as “” but will point to the myData of the
original object. So a change in myData by either original or cloned object will be reflected in other also. But in
deep copying there will be new id object and also new myData object and independent of original object but
with same values.
Shallow copying is default cloning in Java which can be achieved using clone() method of Object class. For
deep copying some extra logic need to be provided.
Q5) What are the characteristics of a shallow clone?
Ans) If we do a = clone(b)
1) Then b.equals(a)
2) No method of a can modify the value of b.
Q6) What are the disadvantages of deep cloning?
Ans) Disadvantages of using Serialization to achieve deep cloning –
Serialization is more expensive than using object.clone().
Not all objects are serializable.
Serialization is not simple to implement for deep cloned object..

Garbage Collections Questions


Q1) Which part of the memory is involved in Garbage Collection? Stack or Heap?
Ans) Heap
Q2)What is responsiblity of Garbage Collector?
Ans) Garbage collector frees the memory occupied by the unreachable objects during the java program by
deleting these unreachable objects.
It ensures that the available memory will be used efficiently, but does not guarantee that there will be
sufficient memory for the program to run.
Q3) Is garbage collector a dameon thread?
Ans) Yes GC is a dameon thread. A dameon thread runs behind the application. It is started by JVM. The
thread stops when all non-dameon threads stop.
Q4)Garbage Collector is controlled by whom?
Ans) The JVM controls the Garbage Collector; it decides when to run the Garbage Collector. JVM runs the
Garbage Collector when it realizes that the memory is running low, but this behavior of jvm can not be
guaranteed.One can request the Garbage Collection to happen from within the java program but there is no
guarantee that this request will be taken care of by jvm.
Q5) When does an object become eligible for garbage collection?
Ans) An object becomes eligible for Garbage Collection when no live thread can access it.
Q6) What are the different ways to make an object eligible for Garbage Collection when it is no
longer needed?
Ans)
1. Set all available object references to null once the purpose of creating the object is served :
String str = "Set the object ref to null";
str = null;
2. Make the reference variable to refer to another object : Decouple the reference variable from the object
and set it refer to another object, so the object which it was referring to before reassigning is eligible for
Garbage Collection.
publc class GarbageCollnTest2 {
public static void main(String [] args){
String str1 = "Garbage collected after use";
String str2 = "Another String";
System.out.println(str1);
//String object referred by str1 is not eligible for GC yet
str1 = str2;
/* Now the str1 variable referes to the String object "Another String" and the object "Garbage collected after
use" is not referred by any variable and hence is eligible for GC */
}
}
3) Creating Islands of Isolation : If you have two instance reference variables which are referring to the
instances of the same class, and these two reference variables refer to each other and the objects referred by
these reference variables do not have any other valid reference then these two objects are said to form an
Island of Isolation and are eligible for Garbage Collection.
public class GCTest3 {
- 63 -
Core Java
GCTest3 g;
public static void main(String [] str){
GCTest3 gc1 = new GCTest3();
GCTest3 gc2 = new GCTest3();
gc1.g = gc2; //gc1 refers to gc2
gc2.g = gc1; //gc2 refers to gc1
gc1 = null;
gc2 = null;
//gc1 and gc2 refer to each other and have no other valid //references
//gc1 and gc2 form Island of Isolation
//gc1 and gc2 are eligible for Garbage collection here
}
}
Q7) Can the Garbage Collection be forced by any means?
Ans) No. The Garbage Collection can not be forced, though there are few ways by which it can be requested
there is no guarantee that these requests will be taken care of by JVM.
Q8) How can the Garbage Collection be requested?
Ans) There are two ways in which we can request the jvm to execute the Garbage Collection.
1) The methods to perform the garbage collections are present in the Runtime class provided by java. The
Runtime class is a Singleton for each java main program.
The method getRuntime() returns a singleton instance of the Runtime class. The method gc() can be invoked
using this instance of Runtime to request the garbage collection.
2) Call the System class System.gc() method which will request the jvm to perform GC.
Q9) What is the purpose of overriding finalize() method?
Ans) The finalize() method should be overridden for an object to include the clean up code or to dispose of
the system resources that should to be done before the object is garbage collected.
Q10) If an object becomes eligible for Garbage Collection and its finalize() method has been called
and inside this method the object becomes accessible by a live thread of execution and is not
garbage collected. Later at some point the same object becomes eligible for Garbage collection,
will the finalize() method be called again?
Ans) No
Q11) How many times does the garbage collector calls the finalize() method for an object?
Ans) Only once.
Q12) What happens if an uncaught exception is thrown from during the execution of the finalize()
method of an object?
Ans) The exception will be ignored and the garbage collection (finalization) of that object terminates.
Q13) What are different ways to call garbage collector?
Ans) Garbage collection can be invoked using System.gc() or Runtime.getRuntime().gc().
Q14) How to enable/disable call of finalize() method of exit of the application
Ans) Runtime.getRuntime().runFinalizersOnExit(boolean value) . Passing the boolean value will either disable
or enable the finalize() call.
What is HashMap and Map?
Map is Interface and Hashmap is class that implements this interface.
What is the significance of ListIterator? Or What is the difference b/w Iterator and ListIterator?
Iterator : Enables you to cycle through a collection in the forward direction only, for obtaining or removing
elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the modification of elements
Difference between HashMap and HashTable? Can we make hashmap synchronized?
1. The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.
(HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.
Note on Some Important Terms
1)Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that
any thread before performing an update on a hashtable will have to acquire a lock on the object while others
will wait for lock to be released.
2)Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and
some other thread tries to modify the collection object "structurally”, a concurrent modification exception will
be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection
"structurally”. However, if prior to calling "set", the collection has been modified structurally,
"IllegalArgumentException" will be thrown.
HashMap can be synchronized by
- 64 -
Core Java
Map m = Collections.synchronizeMap(hashMap);
What is the difference between set and list?
A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores
elements in an ordered way but may contain duplicate elements.
Difference between Vector and ArrayList? What is the Vector class?
Vector is synchronized whereas ArrayList is not. The Vector class provides the capability to implement a
growable array of objects. ArrayList and Vector class both implement the List interface. Both classes are
implemented using dynamically resizable arrays, providing fast random access and fast traversal. In vector
the data is retrieved using the elementAt() method while in ArrayList, it is done using the get() method.
ArrayList has no default size while vector has a default size of 10. when you want programs to run in
multithreading environment then use concept of vector because it is synchronized. But ArrayList is not
synchronized so, avoid use of it in a multithreading environment.
What is an Iterator interface? Is Iterator a Class or Interface? What is its use?
The Iterator is an interface, used to traverse through the elements of a Collection. It is not advisable to
modify the collection itself while traversing an Iterator.
What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.
What is the List interface?
The List interface provides support for ordered collections of objects.
How can we access elements of a collection?
We can access the elements of a collection using the following ways:
1.Every collection object has get(index) method to get the element of the object. This method will return
Object.
2.Collection provide Enumeration or Iterator object so that we can get the objects of a collection one by one.
What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow
duplicate elements.
What’s the difference between a queue and a stack?
Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on First-in-first-
out (FIFO) rule.
What is the Map interface?
The Map interface is used associate keys with values.
What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides
the capability to specify a set of default values to be used.
Which implementation of the List interface provides for the fastest insertion of a new element into
the middle of the list?
a. Vector
b. ArrayList
c. LinkedList
d. None of the above
ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the
middle of the list the elements that follow the insertion point must be shifted to make room for the new
element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of
the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.
How can we use hashset in collection interface?
This class implements the set interface, backed by a hash table (actually a HashMap instance). It makes no
guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain
constant over time. This class permits the Null element.
This class offers constant time performance for the basic operations (add, remove, contains and size),
assuming the hash function disperses the elements properly among the buckets.
What are differences between Enumeration, ArrayList, Hashtable and Collections and Collection?
Enumeration: It is series of elements. It can be use to enumerate through the elements of a vector, keys or
values of a hashtable. You can not remove elements from Enumeration.
ArrayList: It is re-sizable array implementation. Belongs to 'List' group in collection. It permits all elements,
including null. It is not thread -safe.
Hashtable: It maps key to value. You can use non-null value for key or value. It is part of group Map in
collection.
Collections: It implements Polymorphic algorithms which operate on collections.
Collection: It is the root interface in the collection hierarchy.
What is difference between array & arraylist?
- 65 -
Core Java
An ArrayList is resizable, where as, an array is not. ArrayList is a part of the Collection Framework. We can
store any type of objects, and we can deal with only objects. It is growable. Array is collection of similar data
items. We can have array of primitives or objects. It is of fixed size. We can have multi dimensional arrays.
Array: can store primitive ArrayList: Stores object only
Array: fix size ArrayList: resizable
Array: can have multi dimensional
Array: lang ArrayList: Collection framework
Can you limit the initial capacity of vector in java?
Yes you can limit the initial capacity. We can construct an empty vector with specified initial capacity
public vector(int initialcapacity)
What method should the key class of Hashmap override?
The methods to override are equals() and hashCode().
What is the difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove()
method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only
to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and
removing the objects.
So Enumeration is used when ever we want to make Collection objects as Read-only.

Q: What is the Collections API?


A: The Collections API is a set of classes and interfaces that support operations on collections of objects.
Q: What is the List interface?
A: The List interface provides support for ordered collections of objects.
Q: What is the Vector class?
A: The Vector class provides the capability to implement a growable array of objects.
Q: What is an Iterator interface?
A: The Iterator interface is used to step through the elements of a Collection .
Q: Which java.util classes and interfaces support event handling?
A: The EventObject class and the EventListener interface support event processing.
Q: What is the GregorianCalendar class?
A: The GregorianCalendar provides support for traditional Western calendars
Q: What is the Locale class?
A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or
cultural region .
Q: What is the SimpleTimeZone class?
A: The SimpleTimeZone class provides support for a Gregorian calendar .
Q: What is the Map interface?
A: The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
Q: What is the highest-level event class of the event-delegation model?
A: The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.
Q: What is the Collection interface?
A: The Collection interface provides support for the implementation of a mathematical bag - an unordered
collection of objects that may contain duplicates.
Q: What is the Set interface?
A: The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not
allow duplicate elements.
Q: What is the typical use of Hashtable?
A: Whenever a program wants to store a key value pair, one can use Hashtable.
Q: I am trying to store an object using a key in a Hashtable. And some other object already exists
in that location, then what will happen? The existing object will be overwritten? Or the new object
will be stored elsewhere?
A: The existing object will be overwritten and thus it will be lost.
Q: What is the difference between the size and capacity of a Vector?
A: The size is the number of elements actually stored in the vector, while capacity is the maximum number of
elements it can store at a given instance of time.
Q: Can a vector contain heterogenous objects?
A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
Q: Can a ArrayList contain heterogenous objects?
A: Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.
Q: What is an enumeration?

- 66 -
Core Java
A: An enumeration is an interface containing methods for accessing the underlying data structure from which
the enumeration is obtained. It is a construct which collection classes return when you request a collection of
all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.
Q: Considering the basic properties of Vector and ArrayList, where will you use Vector and where
will you use ArrayList?
A: The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is
not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use
Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non
synchronized data structure will give better performance than the synchronized one.
Q: Can a vector contain heterogenous objects?
A: Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.

Q9: What is garbage collection algo ?


Ans: Garbage collection Algo :
Mark-sweep collectors
The most basic form of tracing collector, first proposed by Lisp inventor John McCarthy in 1960, is the mark-
sweep collector, in which the world is stopped and the collector visits each live node, starting from the roots,
and marks each node it visits. When there are no more references to follow, collection is complete, and then
the heap is swept (that is, every object in the heap is examined), and any object not marked is reclaimed as
garbage and returned to the free list. Figure 1 illustrates a heap prior to garbage collection; the shaded blocks
are garbage because they are unreachable by the user program:

Figure 1. Reachable and unreachable objects

Mark-sweep is simple to implement, can reclaim cyclic structures easily, and doesn't place any burden on the
compiler or mutator like reference counting does. But it has deficiencies -- collection pauses can be long, and
the entire heap is visited in the sweep phase, which can have very negative performance consequences on
virtual memory systems where the heap may be paged.
The big problem with mark-sweep is that every active (that is, allocated) object, whether reachable or not, is
visited during the sweep phase. Because a significant percentage of objects are likely to be garbage, this
means that the collector is spending considerable effort examining and handling garbage. Mark-sweep
collectors also tend to leave the heap fragmented, which can cause locality issues and can also cause
allocation failures even when sufficient free memory appears to be available.

Mark-and-Sweep Garbage Collection

This section presents the mark-and-sweep garbage collection algorithm. The mark-and-sweep algorithm was
the first garbage collection algorithm to be developed that is able to reclaim cyclic data structures.
Variations of the mark-and-sweep algorithm continue to be among the most commonly used garbage
collection techniques.
When using mark-and-sweep, unreferenced objects are not reclaimed immediately. Instead, garbage is
allowed to accumulate until all available memory has been exhausted. When that happens, the execution of

- 67 -
Core Java
the program is suspended temporarily while the mark-and-sweep algorithm collects all the garbage. Once all
unreferenced objects have been reclaimed, the normal execution of the program can resume.
The mark-and-sweep algorithm is called a tracing garbage collector because is traces out the entire collection
of objects that are directly or indirectly accessible by the program. The objects that a program can access
directly are those objects which are referenced by local variables on the processor stack as well as by any
static variables that refer to objects. In the context of garbage collection, these variables are called the roots .
An object is indirectly accessible if it is referenced by a field in some other (directly or indirectly) accessible
object. An accessible object is said to be live . Conversely, an object which is not live is garbage.
The mark-and-sweep algorithm consists of two phases: In the first phase, it finds and marks all accessible
objects. The first phase is called the mark phase. In the second phase, the garbage collection algorithm scans
through the heap and reclaims all the unmarked objects. The second phase is called the sweep phase. The
algorithm can be expressed as follows:
for each root variable r
mark (r);
sweep ();

In order to distinguish the live objects from garbage, we record the state of an object in each object. That is,
we add a special boolean field to each object called, say, marked. By default, all objects are unmarked when
they are created. Thus, the marked field is initially false.
An object p and all the objects indirectly accessible from p can be marked by using the following recursive
mark method:
void mark (Object p)

if (!p.marked)

p.marked = true;
for each Object q referenced by p
mark (q);

Notice that this recursive mark algorithm does nothing when it encounters an object that has already been
marked. Consequently, the algorithm is guaranteed to terminate. And it terminates only when all accessible
objects have been marked.
In its second phase, the mark-and-sweep algorithm scans through all the objects in the heap, in order to
locate all the unmarked objects. The storage allocated to the unmarked objects is reclaimed during the scan.
At the same time, the marked field on every live object is set back to false in preparation for the next
invocation of the mark-and-sweep garbage collection algorithm:
void sweep ()

for each Object p in the heap

if (p.marked)
p.marked = false
else
heap.release (p);

Figure illustrates the operation of the mark-and-sweep garbage collection algorithm. Figure (a) shows
the conditions before garbage collection begins. In this example, there is a single root variable. Figure (b)
shows the effect of the mark phase of the algorithm. At this point, all live objects have been marked. Finally,
Figure (c) shows the objects left after the sweep phase has been completed. Only live objects remain in
memory and the marked fields have all been set to false again.

- 68 -
Core Java

Figure: Mark-and-sweep garbage collection.


Because the mark-and-sweep garbage collection algorithm traces out the set of objects accessible from the
roots, it is able to correctly identify and collect garbage even in the presence of reference cycles. This is the
main advantage of mark-and-sweep over the reference counting technique presented in the preceding section.
A secondary benefit of the mark-and-sweep approach is that the normal manipulations of reference variables
incurs no overhead.
The main disadvantage of the mark-and-sweep approach is the fact that that normal program execution is
suspended while the garbage collection algorithm runs. In particular, this can be a problem in a program that
interacts with a human user or that must satisfy real-time execution constraints. For example, an interactive
application that uses mark-and-sweep garbage collection becomes unresponsive periodically.

- 69 -
Core Java
*************************** The "tell me about yourself" **********************
It's a tricky question, though, because the information you reveal about yourself can lead the interviewer to
keep considering you as a candidate, or it can cause them to cross you off the list.
Remember, this question is often used specifically to test your response to it. To keep yourself in the running,
stay away from talking about personal topics. The interviewer doesn't want to hear about your family or
spouse, your hobbies, pets, or personal life. The best way to answer to "tell me about yourself" is to stick to
business.
The interviewer wants to hear what you've done in your career, and what you plan on doing. To give them the
answer they're looking for, it's best to talk about your past career, things you've accomplished, and what
made you decide to apply for this position. Include details about skills you have that directly relate to the job
you are applying for.
While preparing for the answer consider including following points.
1. Introduce yourself:
Tell them your name and which place you are from. Suppose you are "Mike Creamer", then do not start with
"Myself Mike Creamer"; start with "I am Mike Creamer". This is a very common mistake. Not acceptable in
interviews especially in call center jobs.
You may talk about your family (cover up in short); you may talk about your how you came to the city, etc.
A few sentences, and around 30 seconds, should be enough to give your interviewer a positive idea of who
you are and what you've done, as well as put your application in a good context. The following examples
demonstrate this format:
Example 1: My name is Jamie Johnson (1), and I'm a senior at Washington High School (2) where I'm
preparing to go to college for psychology (3). I'm good at public speaking, and I've been a group leader on
several school projects (4). I want to get closer to the subject of psychology, so I think being the receptionist
in a doctor's office would be a good step for me (5).
Example 2: I'm Kurt Smith (1), and I've been a hardware store manager for seven years (2). I'm especially
skilled with electrical hardware (3), and I was previously the supervisor for the store's electrical department
(4). I'd like to move more towards that industry, so I'm applying to be an electrician at your electrical repair
business (5).
Using this format, you can tell your interviewer about your best skills, your recent accomplishments, and why
you're applying, in a way that sounds organized and logical.

2. Your education:
Tell them about your education i.e. graduation/post-graduation. If you are a fresher then tell them the grades
you got. If you have done something different than others then tell them. It surely adds a value!
3. Your experience:
Talk about your whole experience. Start from early years and gradually come to recent years. If you have a
long experience then you must not be doing same thing all years. Then exactly what you were doing? This is
what your interviewer wants to listen. If you are a fresher then talk about your projects.
4. Your experience regarding to the post you has applied for:
This is of most interest to your interviewer. You may be having lot of experience but how much experience
you have regarding current job post is very important. If you do not have it then you can talk about some
related experience. Or if you do not have related experience too then say it clearly. Buy along with it give
them confidence that you can do it and you have genuine interest to do it.
5. Do not describe your salary or pay scale at this point of time (unless explicitly asked).
6. Avoid giving unnecessary details. Value your interviewer's time.
7. The idle answer should not last more than 1 minute.

*********************** By Forum Quest **************************************


Ques: Find The second highest sal from emp
Ans : SELECT * FROM TEST.EMPMST e
WHERE 1=(SELECT count(*) FROM TEST.EMPMST s WHERE s.sal>e.sal)

Statement, PreparedStatement, CallableStatement : More Details read from the below link
“http://www.tutorialspoint.com/jdbc/jdbc-introduction.htm”
Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement,
and PreparedStatement interfaces define the methods and properties that enable you to send SQL or
PL/SQL commands and receive data from your database.
Interfaces Recommended Use

- 70 -
Core Java
Use for general-purpose access to your database. Useful when you are using
Statement static SQL statements at runtime. The Statement interface cannot accept
parameters.

Use when you plan to use the SQL statements many times. The
PreparedStatement
PreparedStatement interface accepts input parameters at runtime.

Use when you want to access database stored procedures. The


CallableStatement
CallableStatement interface can also accept runtime input parameters.
The Statement Objects:
Creating Statement Object:
Before you can use a Statement object to execute a SQL statement, you need to create one using the
Connection object's createStatement( ) method, as in the following example:
Statement stmt = null;
try { stmt = conn.createStatement( ); . . .}
catch (SQLException e) { . . .}
finally { . . .}

Once you've created a Statement object, you can then use it to execute a SQL statement with one of its three
execute methods.
1)boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved;
otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly
dynamic SQL.
2)int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the SQL
statement. Use this method to execute SQL statements for which you expect to get a number of rows affected
- for example, an INSERT, UPDATE, or DELETE statement.
1)ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you expect to
get a result set, as you would with a SELECT statement.
Closing Statement Obeject:
Just as you close a Connection object to save database resources, for the same reason you should also close
the Statement object.
A simple call to the close() method will do the job. If you close the Connection object first it will close
the Statement object as well. However, you should always explicitly close the Statement object to ensure
proper cleanup.
Statement stmt = null;
try {
stmt = conn.createStatement( ); . . .}
catch (SQLException e) { . . .}
finally { stmt.close();}

For a better understanding, I would suggest to study Statement - Example Code.


The PreparedStatement Objects:
The PreparedStatement interface extends the Statement interface which gives you added functionality with a
couple of advantages over a generic Statement object.
This statement gives you the flexibility of supplying arguments dynamically.
Creating PreparedStatement Object:
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL); . . .}
catch (SQLException e) { . . .}
finally { . . .}

All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker. You must
supply values for every parameter before executing the SQL statement.
- 71 -
Core Java
The CallableStatement Objects:
Just as a Connection object creates the Statement and PreparedStatement objects, it also creates the
CallableStatement object which would be used to execute a call to a database stored procedure.
Creating CallableStatement Object:
The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a
CallableStatement object based on the preceding stored procedure:
CallableStatement cstmt = null;
try {
cstmt = conn.prepareCall ("{call getEmpName (?, ?)}");
...
}
catch (SQLException e) { . . .}
finally { . . .}

The String variable SQL represents the stored procedure, with parameter placeholders.
Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate
getXXX() method. This method casts the retrieved value of SQL type to a Java data type.

Ques :How to delete the duplicate record from the same table?
Ans : delete from (
select empid ,EmpName,Designation,ROW_NUMBER() OVER(ORDER BY empid) as row
from test.testt
) as emp
where row >1

Ques :How to find the schema from select statement?


Ans :
SELECT * from SYSCAT.COLUMNS where TABNAME = 'TESTT' and TABSCHEMA ='TEST'

Ques :Diff between String and new String()?


Ans :String is literal and new String() for creating the new objects.
String class overrides the equals() method of the Object class. It compares the content of the two string
object and returns the boolean value accordingly.
For example,
String str1=”Hello”;
String str2=”Hello”;
String str3=new String(”Hello”) //Using constructor.
If(str1 == str2)
System.out.println(“Equal 1”);
Else
System.out.println(“Not Equal 1”);

If(str1 == str3)
System.out.println(“Equal 2”);
Else
System.out.println(“I am constructed using constructor, hence not interned”);
If( str1.equals(str3) )
System.out.println(“Equal 3”);
Else
System.out.println(“Not Equal 3”);

The output would be,


Equal 1
Not Equal 2
Equal 3
Note that == compares the references not the actual contents of the String object; Where as equals method
compares actual contents of two String objects.

Ques : Difference Between Stack and Heap - Java Question

- 72 -
Core Java
Ans :Heap: in heap memory objects will be created.whenever JVM loads a class,a method and heap area are
immediately created in it.Class varibles and object always on Heap.
stack:this is the place where java methods are executed,each method is executed on a separate frame in
java stack. local variables of ALL methods live always on the stack.

Question and Ans :


Ques 1: Can you define the methods in scriplet ?
Ans : I can not be placed method inside of scriplet tags, I can only be declared in declarations tags. Example :
<% // Can,t define method %> In scriplet I can not define the method because whenever I will define the
method and variable in scriplet tag and when the jsp page is converted in to servlet that time all these will go
in the service method, we know that the within one method we can not define another method. But in
declaration part we can define and can be used because we know that whenever anything is define in the
declaration tag and after converting the servlet will resides out of service method.
<%!
public String testss(){
return "Morning";
}
%>

And using like this  <td> Good <%=testss()%> </td> & result will as Good Morning

Ques 2: Can you define the methods in scriplet ?


Ans : ========================= test.jsp ==================
<%@ taglib uri="/Taglibs" prefix="testTags" %>
<HTML>
<HEAD>
<TITLE> First Custom Tag </TITLE>
</HEAD>
<BODY>
<testTags:TestTag> </testTags:TestTag> // Here using the custum tags
</BODY>
</BODY>
</HTML>

=================== web.xml =====================

<taglib>
<taglib-uri>/Taglibs</taglib-uri>
<taglib-location>/WEB-INF/tlds/hello.tld </taglib-location>
</taglib>
=================== hello.tld ==========================

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>patel</short-name>
<description>Simple example example library.Author:shiva</description>

<tag>
<name>TestTag</name>
<tag-class>MVCDemo.HelloTag</tag-class>
<body-content>JSP</body-content>
<description>
Simple hello world example.

- 73 -
Core Java
take no attribute and simply generate HTML.
</description>

</tag>
</taglib>

================== HelloTag.java ==================

package MVCDemo;
import java.io.IOException;
import java.util.Date;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.TagSupport;

public class HelloTag extends TagSupport{

public int doStartTag() throws JspTagException{


return EVAL_BODY_INCLUDE;
}

public int doEndTag() throws JspTagException{


String dateString=new Date().toString();
try{
//pageContext.getOut().write("<marquee>hello world.</marquee>");
for(int i=1;i<=2;i++)
pageContext.getOut().write("<input type='text' name='test"+i+"'><br><br>");
}catch(IOException ex){
throw new JspTagException("Fatal Error: hello tag could not write to jsp
out");
}
return EVAL_PAGE;
}
}
Ques 3: What is difference between include action and include directive ?
Ans : <%@ include>: Used to include static resources during translation time. JSP include: Used to include
dynamic content or static content during runtime.

Ques 4: How the exceptions are handled in struts?


Exceptions in Struts are handled in two ways:
Programmatic exception handling : Explicit try/catch blocks in any code that can throw exception.
It works well when custom value (i.e., of variable) needed when error occurs.
Declarative exception handling :You can either define <global-exceptions> handling tags in your
struts-config.xml or define the exception handling tags within <action></action> tag. It works well
when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.
<global-exceptions>
<exception key="some.key" type="java.lang.NullPointerException" path="/WEB-INF/errors/null.jsp"/>
</global-exceptions>

or
<exception key="some.key" type="package.SomeException" path="/WEB-INF/somepage.jsp"/>

Ques 5:What is the difference between doGet() and doPost()?


Ans : GET Method : Using get method we can able to pass 2K data from HTML All data we are passing to
Server will be displayed in URL (request string).
POST Method : In this method we does not have any size limitation. All data passed to server will be hidden,
User cannot able to see this info on the browser.
Ques 6: What is the difference between HttpServlet and GenericServlet?
- 74 -
Core Java
Ans : Servlet Interface is the central abstraction. All servlets implements this Servlet
Interface either directly or indirectly ( may implement or extend Servlet Interfaces sub classes or sub interfaces)
Servlet
|
Generic Servlet
|
HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests
|
MyServlet

A GenericServlet has a service() method to handle requests. HttpServlet extends GenericServlet added new
methods :doGet(),doPost(),doHead(),doPut(),doOptions() doDelete(),doTrace() methods Both these classes are
abstract.
Ques 7:What return ?
Ans : public class TryCatch {
public int intTest(){
try{
int i = 10/0;
System.out.println("This is try");
}catch(ArithmeticException a){
System.out.println("In Catch");
//System.exit(0); // Does not return anything becz sytem exit
return 1;
}finally{
System.out.println("In finally");
return 2;
}
}
public String test(){
return null; // This is true and return null
}

public static void main(String args[]){


TryCatch t = new TryCatch();
System.out.println("Test :"+t.intTest());
//System.out.println("Test :"+t.test());
}
}

OutPut :
In Catch
In finally
Test :2 // From finally

Ques 8:What is connection pooling and how to create the class for conn pooling ?
Ans : Creating a connection to the database server is expensive. It is even more expensive if the
server is located on another machine. Connection pool contains a number of open database
connections with minimum and maximum connections, that means the connection pool has open
connections between minimum and maximum number that you specify. The pool expands and
shrinks between minimum and maximum size depending on incremental capacity. You need to give
minimum, maximum and incremental sizes as properties to the pool in order to maintain that
functionality. You get the connection from the pool rather directly .For example, if you give
properties like min, max and incremental sizes as 3, 10 and 1 then pool is created with size 3
initially and if it reaches it's capacity 3 and if a client requests a connection concurrently, it
increments its capacity by 1 till it reaches 10 and later on it puts all its clients in a queue.
- 75 -
Core Java
There are a few choices when using connection pool.
1. You can depend on application server if it supports this feature, generally all the application
servers support connection pools. Application server creates the connection pool on behalf of you
when it starts. You need to give properties like min, max and incremental sizes to the application
server.
2. You can use JDBC 2.0 interfaces, ConnectionPoolDataSource and PooledConnection if your
driver implements these interfaces
3. Or you can create your own connection pool if you are not using any application server or JDBC
2.0 compatible driver.
By using any of these options, you can increase performance significantly. You need to take care of
properties like min, max and incremental sizes. The maximum number of connections to be given
depends on your application's requirement that means how many concurrent clients can access
your database and also it depends up on your database's capability to provide maximum number of
connections.
try{
Connection con = null;
String jndiDB2LookupName = “jdbcConnPool”; // also get the value from prop.
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup(jndiDB2LookupName);
con = ds.getConnection();
}catch (java.sql.SQLException e) {
e.printStackTrace();
}

DataSource : DataSource is interface and A DataSource object is the representation of a data source in the
Java programming language. In basic terms, a data source is a facility for storing data. It can be as
sophisticated as a complex database for a large corporation or as simple as a file with rows and columns. A
data source can reside on a remote server, or it can be on a local desktop machine. Applications access a data
source using a connection, and a DataSource object can be thought of as a factory for connections to the
particular data source that the DataSource instance represents. The DataSource interface provides two
methods for establishing a connection with a data source.
Using a DataSource object is the preferred alternative to using the DriverManager for establishing a
connection to a data source. They are similar to the extent that the DriverManager class and DataSource
interface both have methods for creating a connection, methods for getting and setting a timeout limit for
making a connection, and methods for getting and setting a stream for logging.

Ques 9:How to create the connection?


Ans :
String driverClass = “com.ibm.db2.jcc.DB2Driver";
String dbUrl = “jdbc:db2://136.51.156.131:50000/EHLPDEVTest”;
String dbUser = “abcdd”;
String dbPassword = “hsbcccc”;
Connection con = null;
try{
Class.forName(driverClass);
con = DriverManager.getConnection(dbUrl,dbUser,dbPassword);
}catch(Exception exp){
System.err.println("Could not connect to dtabase.\n"+exp.getMessage());
}

Ques 10:Difference between Struts 1.2 and Struts 2.0?


Ans : difference between Struts 1.x and Struts 2.x

Feature Struts 1 Struts 2


Action classesStruts1 extends the abstract base class by its While in Struts 2 an Action class implements an
action class. The problem with struts1 is that Action interface along with other interfaces use

- 76 -
Core Java
optional and custom services. Struts 2 provides
a base ActionSupport class that implements
it uses the abstract classes rather than commonly used interfaces. Although an Action
interfaces. interface is not necessary any POJO object
along with an execute signature can be used as
an Struts 2 Action object.
Struts 1 Actions are singletons therefore they
Struts 2 doesn't have thread-safety issues as
must be thread-safe because only one
Action objects are instantiated for each request.
instance of a class handles all the requests for
Threading A servlet container generates many throw-away
that Action. The singleton strategy restricts to
Model objects per request and one more object does
Struts 1 Actions and requires extra care to
not impose a performance penalty or impact
make the action resources thread safe or
garbage collection.
synchronized while developing an application.
Container does not treat the Struts 2 Actions as
a couple. Servlet contexts are typically
Actions are dependent on the servlet API
represented as simple Maps that allow Actions
because HttpServletRequest and
Servlet to be tested in isolation. Struts 2 Actions can
HttpServletResponse is passed to the execute
Dependency still access the original request and response if
method when an Action is invoked therefore
required. While other architectural elements
Struts1.
directly reduce or eliminate the need to access
the HttpServetRequest or HttpServletResponse.
Struts1 application has a major problem while
To test the Struts 2 Actions instantiate the
testing the application because the execute
Action set the properties and invoking methods.
Testability method exposes the Servlet API. Struts
Dependency Injection also makes testing
TestCase provides a set of mock object for
easier.
Struts 1.
Struts 1 recieves an input by creating an Struts 2 requires Action properties as input
ActionForm object. Like the action classes all properties that eliminates the need of a second
ActionForms class must extend a ActionForm input object. These Input properties may be
Harvesting base class. Other JavaBeans classes cannot be rich object types since they may have their own
Input used as ActionForms while developers create properties. Developer can access the Action
redundant classes to receive the input. properties from the web page using the taglibs.
DynaBeans is the best alternative to create Struts 2 also supports the ActionForm pattern
the conventional ActionForm classes. POJO form objects and POJO Actions as well.
Struts1 integrates with JSTL so it uses the Struts 2 can use JSTL but the framework also
Expression JSTL EL. The EL has basic object graph supports a more powerful and flexible
Language traversal but relatively weak collection and expression language called "Object Graph
indexed property support. Notation Language" (OGNL).
Struts 2 uses a ValueStack technology to make
the values accessible to the taglibs without
Binding coupling the view to the object to which it is
Struts 1 binds objects into the page context by
values into rendering. The ValueStack strategy enables us
using the standard JSP mechanism.
views to reuse views across a range of types having
same property name but different property
types.
Struts 1 ActionForm properties are almost in
the form of Strings. Commons-Beanutils are Struts 2 uses OGNL for type conversion and
Type
used by used by Struts 1 for type conversion. converters to convert Basic and common object
Conversion
Converters are per-class which are not types and primitives as well.
configurable per instance.
Struts 2 allows manual validation that is done
Struts 1 uses manual validation that is done
by using the validate method and the XWork
via a validate method on the ActionForm or by
Validation framework. The Xwork Validation
using an extension to the Commons Validator.
Validation Framework allows chaining of validations into
Classes can have different validation contexts
sub-properties using the validations defined for
for the same class while chaining to
the properties class type and the validation
validations on sub-objects is not allowed.
context.
Control Of Each module in Struts 1 has a separate In Struts 2 different lifecycles are created on a
Action Request Processors (lifecycles) while all the per Action basis via Interceptor Stacks. Custom

- 77 -
Core Java
Actions in the module must share the same stacks are created and used with different
Execution
lifecycle. Actions as

Ques 11: Difference between == and equals() ?


Ans : == is used for the compare the objcets where as the equals() is used to compare the content of the
object.
(==)operator checks if both object references refer to the same memory location eg: if (a== b) it means it
verifies whether both a and b refer to the same location in memory.
equals() if for content comparison.
eg:
String a =”Shiva” ;
String b =”Shiva” ;
String c = “test” ;
if (a.equals(b)) returns true bcoz both contains the same content.
if (a.equals(c)) returns false bcoz a and c contents are different.
if (a ==b) returns true bcoz both contains at the same hashcode.
Ques 12: what is difference between string and stringBuffer
Ans : String variable is immutable. So once you declare it you are not able to modify it. But StringBuffer class
is mutable. You can change the content of StringBuffer variable.
For example:
String msg = "Hello";
msg += " World";
Here the original String "Hello" is not changed. Instead, a new String is created with the value "Hello World"
and assigned to the variable msg. It is important to note that though the String object is immutable, the
reference variable is not.
If you construct two Strings using the same String literal without the new keyword, then only one String
object is created. For example:
String s1 = "hello";
String s2 = "hello";
Here, both s1 and s2 point to the same String object in memory. As we said above, String objects are
immutable. So if we attempt to modify s1, a new modified String is created. The original String referred to by
s2, however, remains unchanged.
StringBuffer
StringBuffer objects are mutable, which means their contents can be changed. For example:
Ex String str = “abc” ;
str = str+ “Hello” ; this will create new memory location and stores new String
but in String buffer
StringBuffer sb = new StringBuffer("123");
sb.append("456"); // Now s contains "123456" it will overwrite in same memory location
Ques 13: what is difference between string and stringBuffer
Ans : Difference between SQL-Server2000 and SQL-Server2005
1.sql server 2005 include enterprise manger and query analyser together in same window we can open many
window tabs in same place but in 2000 it is in different.
2. sql server 2005 support more new datatype like xml
3. we can make more database 2(paw(20))-1 in 2005 in compare to 2000 where not possible so much
database
4. in storeprocedure we can write try catch statemenet in 2005 not in 2000
SQL-server 2005 New features:
Enterprise Data Management
High Availability : Failover clustering and database mirroring technology in SQL Server 2005 enables
enterprises to deliver highly reliable, available applications to employees, customers, and partners.
Management Tools : SQL Server 2005 introduces an integrated suite of management tools and management
application programming interfaces (APIs) to provide ease of use, manageability, and support for operating
large-scale SQL Server deployments.
Security Enhancements :SQL Server 2005 has been designed to help provide the highest level of security
for enterprise data through features such as database encryption, more secure default settings, password
policy enforcement, granular permissions control, and an enhanced security model.
Scalability :Scalability advancements in SQL Server 2005 include table partitioning, replication
enhancements, and 64-bit support.

- 78 -
Core Java
Business Intelligence
Analysis Services:
Integration Services
Reporting Services :

Ques 14: Mixed Quest ?


Ans :
public static void main(String args[]) {
try{
System.out.println("A");
return;
}catch(Exception e){
System.out.println("B");
return;
}finally{
System.out.println("C");
return;
}
}
Ans : A,C

public void test(String ss,int... x){


System.out.println("The String is "+ss);
System.out.println("The int is "+x[0]);
}
public void test1(int... x){
System.out.println("Tasdfasdsa is "+x[4]);
}

public static void main(String[] args) {


VariableArgumentsupport obj = new VariableArgumentsupport();
obj.test("Shiva",2);
obj.test("Shiva1",6,4);
obj.test1(2,4,5,5,8,5);
}}

Ques 16: Difference between Statement, PreparedStatement and CallableStatement ?


Ans : More Details read from the below link
“http://www.tutorialspoint.com/jdbc/jdbc-introduction.htm”
Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement,
and PreparedStatement interfaces define the methods and properties that enable you to send SQL or
PL/SQL commands and receive data from your database.
Interfaces Recommended Use

Use for general-purpose access to your database. Useful when you are using
Statement static SQL statements at runtime. The Statement interface cannot accept
parameters.

Use when you plan to use the SQL statements many times. The
PreparedStatement
PreparedStatement interface accepts input parameters at runtime.

Use when you want to access database stored procedures. The


CallableStatement
CallableStatement interface can also accept runtime input parameters.

Ques 17: How to execute the query by Statement ?


Ans : Connection conn = con.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select USER_ID,USER_NAME from Test");

- 79 -
Core Java
while ( rs.next() ) {
System.out.println(rs.getString("USER_ID"));
}
Ques 18: What is AJAX and How to implement it ?
Ans : AJAX = Asynchronous JavaScript and XML
AJAX is not a new programming language, but a technique for creating better, faster, and more interactive
web applications.
With AJAX, your JavaScript can communicate directly with the server, using the JavaScript XMLHttpRequest
object. With this object, your JavaScript can trade data with a web server, without reloading the page.
AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing
web pages to request small bits of information from the server instead of whole pages.
The AJAX technique makes Internet applications smaller, faster and more user-friendly.
AJAX is a browser technology independent of web server software.
AJAX is based on Web Standards
AJAX is based on the following web standards:
 JavaScript
 XML
 HTML
 CSS
The web standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are
browser and platform independent.

The event is as onkeyup=onFillValue()


function onFillValue()
{
var userid = document.frmAJAX.txtuserid.value;
showHintAccount(userid);
}
function showHintAccount(userid)
{
var url= "../servlet/com.ehelp.controller.RequestHandler?
hidRequestId=AJAXCHECKDATA&USERIDS="+userid;
loadXMLDoc(url);
}
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
if (xmlhttp!=null) {
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{
if (xmlhttp.status==200)
{
document.frmAJAX.cmbUserID.length = 0;
var retText = xmlhttp.responseText;
//alert("retText.length :"+retText.length);
if(retText.length != 10){
var word=retText.split(",");
for (i = 0; i <= word.length-2; i++){
addOption(document.frmAJAX.cmbUserID,word[i],word[i]);
- 80 -
Core Java
}
}
else
{
addOption(document.frmAJAX.cmbUserID,"No Data Found","xx");
document.getElementById("txtHint").innerHTML="There are no Records.";

}
}
}
}

What's the different forward and sendRedirect?


RequestDispatcher.forward() and HttpServletResponse.sendRedirect() are the two methods available for
URL redirecting to another jsp or servlet.
sendRedirect() is more flexible than forward() because with sendRedirect() you can connect to any
URL outside the webapplication whereas forward() will work only within the web application.
sendRedirect() is slower than forward() .
sendRedirect() is on the client side whereas forward() is on the server side.

Ans2: What is Design Pattern and how many types and which is used in your project ?
If a problem occurs over and over again, a solution to that problem has been used effectively. That solution is
described as a pattern. The design patterns are language-independent strategies for solving common object-
oriented design problems.
Why Use Patterns?
They have been proven. Patterns reflect the experience, knowledge and insights of developers who have
successfully used these patterns in their own work.
They are reusable. Patterns provide a ready-made solution that can be adapted to different problems as
necessary.
They are expressive. Patterns provide a common vocabulary of solutions that can express large
solutions succinctly.
Pattern Name Description

Business Delegate Reduce coupling between Web and Enterprise JavaBeans TM tiers

Composite Entity Model a network of related business entities

Composite View Separately manage layout and content of multiple composed views

Data Access Object (DAO) Abstract and encapsulate data access mechanisms

Front Controller Centralize application request processing

Model-View-Controller Decouple data representation, application behavior, and presentation

Service Locator Simplify client access to enterprise business services

Session Facade Coordinate operations between multiple business objects in a workflow

Transfer Object Transfer business data between tiers

Singleton A class distributes the only instance of itself.

A class extends another class, takes in an object, and makes the taken
Adapter
object behave like the extended class.

An object encapsulates everything needed to execute a method in another


Command
object.

- 81 -
Core Java
Singleton Pattern
This is one of the most commonly used patterns. There are some instances in the application where we have
to use just one instance of a particular class. Let’s take up an example to understand this.
A very simple example is say Logger, suppose we need to implement the logger and log it to some file
according to date time. In this case, we cannot have more than one instances of Logger in the application
otherwise the file in which we need to log will be created with every instance.
We use Singleton pattern for this and instantiate the logger when the first request hits or when the server is
started.
Difference between static class and static method approaches:
One question which a lot of people have been asking me. What’s the difference between a singleton class and
a static class? The answer is static class is one approach to make a class “Singleton”.
We can create a class and declare it as “final” with all the methods “static”. In this case, you can’t create any
instance of class and can call the static methods directly.
/**
* A utility class of which at most one instance can exist per VM. Use Singleton.instance() to access this
instance.
*/
public class Singleton {
/**
* The constructor could be made private to prevent others from instantiating this class. But this would also
make it impossible to create instances of Singleton subclasses.
*/
protected Singleton() { }

// A handle to the unique Singleton instance.


static private Singleton instance = null;
//@return The unique instance of this class.
static public Singleton instance() {
if(null == instance) {
instance = new Singleton();
}
return instance;
}
}

Example:
final class Logger {
//a static class implementation of Singleton pattern
static public void logMessage(String s) {
System.out.println(s);
}
}// End of class
//==============================
public class StaticLogger {
public static void main(String args[]) {
Logger.logMessage("This is SINGLETON");
}
}// End of class
The advantage of this static approach is that it’s easier to use. The disadvantage of course is that if in future
you do not want the class to be static anymore, you will have to do a lot of recoding.

Factory Pattern
When to use a Factory Pattern?
The Factory patterns can be used in following cases:
1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. In programmer’s language (very raw form), you can use factory pattern where you have to create an object
of any one of sub-classes depending on the data provided.

Adapter Pattern

- 82 -
Core Java
The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is
called an Adapter. This is something like we convert interface of one class into interface expected by the
client. We do that using an Adapter
Let's try and understand this with the help of an example. Again, I will like to take a general example. We all
have electric sockets in our houses of different sizes and shapes. I will take an example of a socket of 15
Ampere. This is a bigger socket and the other one which is smaller is of 5 Ampere. A 15 Amp plug cannot fit
into a 5 Amp socket. Here, we will use an Adapter. The adapter can be called a connector here. The connector
connects both of these and gives output to the client plug which is of 5 Amp.
The Adapter is something like this. It will be having the plug of suitable for 15 Amp and a socket suitable for a
5 Amp plug. So, that the 5 Amp plug which here is the client can fit in and also the server which here is the 15
Amp socket can give the output.
Let's try and convert the same example into a software program. How do we do this? Let's try and understand
the problem once more. We have a 5 Amp plug and want a 5 Amp socket so that it can work. We DO NOT
have a 5 Amp socket, what we have is a 15 Amp socket in which the 5 Amp plug cannot fit. The problem is
how to cater to the client without changing the plug or socket.
This is how the Adapter pattern works. When one interface cannot be changed and has to be suited to the
again cannot-be-changed client, an adapter is used so that both the interfaces can work together.
Facade Pattern
Facade as the name suggests means the face of the building. The people walking past the road can only see
this glass face of the building. They do not know anything about it, the wiring, the pipes and other
complexities. The face hides all the complexities of the building and displays a friendly face.
This is how facade pattern is used. It hides the complexities of the system and provides an interface to the
client from where the client can access the system. In Java, the interface JDBC can be called a facade. We as
users or clients create connection using the “java.sql.Connection” interface, the implementation of which we
are not concerned about. The implementation is left to the vendor of driver.
All in all, the Façade pattern hides the complexities of system from the client and provides a simpler interface.
Looking from other side, the facade also provides the implementation to be changed without affecting the
client code.
Command Pattern
This is another of the data-driven pattern. The client invokes a particular module using a command. The client
passes a request, this request gets propagated as a command. The command request maps to particular
modules. According to the command, a module is invoked.
This pattern is different from the Chain of Responsibility in a way that, in the earlier one, the request passes
through each of the classes before finding an object that can take the responsibility. The command pattern
however finds the particular object according to the command and invokes only that one.
It’s like there is a server having a lot of services to be given, and on Demand (or on command), it caters to
that service for that particular client.
A classic example of this is a restaurant. A customer goes to restaurant and orders the food according to
his/her choice. The waiter/ waitress takes the order (command, in this case) and hands it to the cook in the
kitchen. The cook can make several types of food and so, he/she prepares the ordered item and hands it over
to the waiter/waitress who in turn serves to the customer.
Now, here, the waiter takes command and wraps it in an order, the order is associated to a particular
customer. For, the cook, the order is associated to a cook and also Food is associated to the Order.
The order is an object which depends on the command. The food item will change as soon as the command
changes. This is loose-coupling between the client and the implementation.

what is difference between string and stringBuffer


Ans String variable is immutable. So once you declare it you are not able to modify it. But StringBuffer class
is mutable. You can change the content of StringBuffer variable.
For example:
String msg = "Hello";
msg += " World";
Here the original String "Hello" is not changed. Instead, a new String is created with the value "Hello World"
and assigned to the variable msg. It is important to note that though the String object is immutable, the
reference variable is not.
If you construct two Strings using the same String literal without the new keyword, then only one String
object is created. For example:
String s1 = "hello";
String s2 = "hello";

- 83 -
Core Java
Here, both s1 and s2 point to the same String object in memory. As we said above, String objects are
immutable. So if we attempt to modify s1, a new modified String is created. The original String referred to by
s2, however, remains unchanged.
StringBuffer
StringBuffer objects are mutable, which means their contents can be changed. For example:
Ex String str = “abc” ;
str = str+ “Hello” ; this will create new memory location and stores new String
but in String buffer
StringBuffer sb = new StringBuffer("123");
sb.append("456"); // Now s contains "123456" it will overwrite in same memory location

Opps Concept :
Ques :what is the difference between runtime polimorphism, and compiletime polimorphism ?
Ans : Runtime polymorphism means overriding using inheritance - (same method name same parameter list
same return type same )
Compile-time polymorphism means Overloading (- same method name different parameter list)

Q :Difference between String, StringBuffer and StringBuilder


Ans :String is immutable whereas StringBuffer and StringBuilder can change their values.
The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas
StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better
to use StringBuilder. StringBuilder is more efficient than StringBuffer.
Criteria to choose among String, StringBuffer and StringBuilder
If your text is not going to change use a string Class because a String object is immutable.
1. If your text can change and will only be accessed from a single thread, use a StringBuilder because
StringBuilder is unsynchronized.
2. If your text can changes, and will be accessed from multiple threads, use a StringBuffer because
StringBuffer is synchronous.
Ans :What is a Java Thread and How does it work?
A java thread is an execution context process. Programmer may use java thread mechanism to execute
multiple tasks at the same time.
Basic support for threads is in the java.lang.Thread class
The run() method gives a thread something to do. Its code should implement the thread's running
behavior.
There are two ways of creating a customized thread:
Sub classing java.lang.Thread and Overriding run() method.
Implementing the java.lang.Runnable Interface.
The Life Cycle of a Thread
The following diagram illustrates the various states that a Java thread can be in at any point during its life and
which method calls cause a transition to another state.

1)New state – After the creations of Thread instance the thread is in this state but before the start()
methodinvocation. At this point, the thread is considered not alive.

2)Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters
runnable state after the invoking of start() method but a thread can return to this state after either running,
waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the
processor.
A thread starts its life cycle with a call to start(). For example
- 84 -
Core Java
MyThread aThread = new MyThread();
aThread.start();

3)Running state – A thread is in running state that means the thread is currently executing. There are
several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler
select a thread from runnable pool.
4)Dead state – A thread can be considered dead when its run() method completes. If any thread comes on
this state that means it cannot ever run again.
5)Blocked - A thread can enter in this state because of waiting the resources that are hold by another
thread.

Different states implementing Multiple-Threads are:

As we have seen different states that may be occur with the single thread. A running thread can enter to any
non-runnable state, depending on the circumstances. A thread cannot enters directly to the running state
from non-runnable state, firstly it goes to runnable state. Now lets understand the some non-runnable states
which may be occur handling the multithreads.
Sleeping – On this state, the thread is still alive but it is not runnable, it might be return to runnable state
later, if a particular event occurs. On this state a thread sleeps for a specified amount of time. You can use the
method sleep( ) to stop the running state of a thread.

what is the main difference between jdk1.4 and jdk1.5


Jdk 1.5 has various feature which was not in jdk 1.4. These new features are below-
1)Annotation
2)AutoBoxing
3)Enum support
4)ForEach
5)Generic implemention of Class Method WildCards Bounded Type.
6)Variable Argument support.
In JDK 1.5 there are many new IO classes enhanced for loop autoboxing (i.e. we can directly use the
Wrapper classes are primitive data types.) For example
Integer a 10; where as in JDK 1.4 it is not possible. These are the main differences.
You may have already seen reports about some of the new Java Language changes that comprise the Ease of
Development theme.
Generic Types
Generic types have been widely anticipated by the Java Community and are now part of J2SE 5.0. One of the
first places to see generic types in action is the Collections API. The Collections API provides common
functionality like LinkedLists, ArrayLists and HashMaps that can be used by more than one Java type. The next
example uses the 1.4.2 libraries and the default javac compile mode.

- 85 -
Core Java
ArrayList list = new ArrayList();
list.add(0, new Integer(42));
int total = ((Integer)list.get(0)).intValue();
The cast to Integer on the last line is an example of the typecasting issues that generic types aim to prevent.
The issue is that the 1.4.2 Collection API uses the Object class to store the Collection objects, which means
that it cannot pick up type mismatches at compile time. The first notification of a problem is a
ClassCastException at runtime.
The same example with the generified Collections library is written as follows:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = list.get(0).intValue();
The user of a generified API has to simply declare the type used at compile type using the <> notation. No
casts are needed and in this example trying to add a String object to an Integer typed collection would be
caught at compile time.
Generic types therefore enable an API designer to provide common functionality that can be used with
multiple data types and which also can be checked for type safety at compile time.
Designing your own Generic APIs is a little more complex that simply using them. To get started look at the
java.util.Collection source and also the API guide.
Autoboxing and Auto-Unboxing of Primitive Types
Converting between primitive types, like int, boolean, and their equivalent Object-based counterparts like
Integer and Boolean, can require unnecessary amounts of extra coding, especially if the conversion is only
needed for a method call to the Collections API, for example.
The autoboxing and auto-unboxing of Java primitives produces code that is more concise and easier to follow.
In the next example an int is being stored and then retrieved from an ArrayList. The 5.0 version leaves the
conversion required to transition to an Integer and back to the compiler.
Before
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = (list.get(0)).intValue();
After
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);
Enhanced for Loop
The Iterator class is used heavily by the Collections API. It provides the mechanism to navigate sequentially
through a Collection. The new enhanced for loop can replace the iterator when simply traversing through a
Collection as follows. The compiler generates the looping code necessary and with generic types no additional
casting is required.
Before
ArrayList<Integer> list = new ArrayList<Integer>();
for (Iterator i = list.iterator(); i.hasNext();) {
Integer value=(Integer)i.next();
}
After
ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i : list) { ... }

Enumerated Types
This type provides enumerated type when compared to using static final constants. If you have previously
used the identifier enum in your own application, you will need to adjust the source when compiling with javac
-source 1.5 (or its synonym -source 5).
public enum StopLight { red, amber, green };
Varargs
The varargs functionality allows multiple arguments to be passed as parameters to methods. It requires the
simple ... notation for the method that accepts the argument list and is used to implement the flexible number
of arguments required for printf.

void argtest(Object ... args) {


for (int i=0;i <args.length; i++) {
}
}

- 86 -
Core Java
argtest("test", "data");

Concurrency Utilities
The concurrency utility library, led by Doug Lea in JSR-166, is a special release of the popular concurrency
package into the J2SE 5.0 platform. It provides powerful, high-level thread constructs, including executors,
which are a thread task framework, thread safe queues, Timers, locks (including atomic ones), and other
synchronization primitives.
One such lock is the well known semaphore.The following example uses just one semaphore, also known as a
binary semaphore. See the java.util.concurrent package for more information.

final private Semaphore s= new Semaphore(1, true);

s.acquireUninterruptibly(); //for non-blocking version use s.acquire()

try {
balance=balance+10; //protected value
} finally {
s.release(); //return semaphore token
}

Scalability and Performance


The 5.0 release promises improvements in scalability and performance, with a new emphasis on startup time
and memory footprint, to make it easier to deploy applications running at top speed.
Performance ergonomics are a new feature in J2SE 5.0. This means that if you have been using specialized
JVM runtime options in previous releases, it may be worth re-validating your performance with no or minimal
options.
Monitoring and Manageability
Monitoring and Manageability is a key component of RAS (Reliability, Availability, Serviceability) in the Java
platform.
New JVM Profiling API (JSR-163)
The release also contains a more powerful native profiling API called JVMTI. This API has been specified
through JSR-163 and was motivated by the need for an improved profiling interface. However, JVMTI is
intended to cover the full range of native in-process tools access, which in addition to profiling, includes
monitoring, debugging and a potentially wide variety of other code analysis tools.
The implementation includes a mechanism for bytecode instrumentation, Java Programming Language
Instrumentation Services (JPLIS). This enables analysis tools to add additional profiling only where it is
needed. The advantage of this technique is that it allows more focused analysis and limits the interference of
the profiling tools on the running JVM. The instrumentation can even be dynamically generated at runtime, as
well as at class loading time, and pre-processed as class files.

Enhancements in JDK 5.0


The following are some of the enhancements made for improved program execution speed in JDK 5.0.
 Garbage collection ergonomics - Provides for the automatic detection and choice of the client or
server runtime compiler, which enhances performance on server-class machines. See "Server-Class Machine
Detection" and "Garbage Collection Ergonomics" at Java Virtual Machines for more information.
 StringBuilder class - The addition of a new class StringBuilder that works essentially as an
unsynchronized StringBuffer for performance enhancement. You should replace all StringBuffer uses with
StringBuilder unless you need the synchronization (which you almost certainly don't). StringBuilder is almost
always faster than StringBuffer.
 Java 2DTM technology - These Java 2D performance enhancements have spin-off performance
benefits in other areas of functionality such as Swing/JFC. Examples include improved acceleration for
BufferedImage objects, support for hardware-accelerated rendering using OpenGL, and improved text-
rendering performance. See New Java 2D Features for more information.
 Image I/O - Performance and memory usage improvements have been made when reading and
writing JPEG images. See "Improved Performance" at Image I/O Features.

Ques 15: EJB Quest EJB Interview Questions?


1.What is EJB ?

- 87 -
Core Java
EJB stands for Enterprise JavaBean and is a widely-adopted server side component architecture for J2EE. It
enables rapid development of critical application that arereusable and portable across middleware while
protecting IT investment and preventing vendor lock-in.
2 . What is session Facade?
Session Facade is a design pattern to access the Entity bean through local interface than accessing directly. It
increases the performance over the network. In this case we call session bean which on turn call entity bean.
3 . What is EJB role in J2EE?
EJB technology is the core of J2EE. It enables developers to write reusable and portable server-side business
logic for the J2EE platform.
4 . What is the difference between EJB and Java beans?
EJB is a specification for J2EE server, not a product; Java beans may be a graphical component in IDE
5 . What are the key features of the EJB technology?
1. EJB components are server-side components written entirely in the Java programming language
2. EJB components contain business logic only - no system-level programming & services, such as
transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB
component by the EJB server.
3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure.
4. EJB components are fully portable across any EJB server and any OS.
5. EJB architecture is wire-protocol neutral–any protocol can be utilized like IIOP,JRMP, HTTP, DCOM,etc.
6 . What are the key benefits of the EJB technology?
1. Rapid application development
2. Broad industry adoption
3. Application portability
4. Protection of IT investment
7 . How many enterprise beans?
There are three kinds of enterprise beans:
1. session beans,
2. entity beans, and
3. message-driven beans.
8 . What is message-driven bean?
A message-driven bean combines features of a session bean and a Java Message Service (JMS) message
listener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clients
to access the business logic in the EJB tier.
9 . What is Entity Bean and Session Bean ?
Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of
the business methods.
There are two types of Entity Bean:
1)Container Managed Persistence(CMP)
2)Bean-Managed Persistence(BMP).
Session Bean is used to represent a workflow on behalf of a client.
There are two types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn’t maintain any
conversational state with clients between method invocations. Stateful bean maintains state between
invocations.
10 . How EJB Invocation happens?
Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference to the client.
Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. Return
EJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request to
Bean (Enterprise Bean).
11 . Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a
value in the HttpSession from inside an EJB?
You can pass the HttpSession as parameter to an EJB method, only if all objects in session are erializable.This
has to be consider as passed-by-value, that means that it’s read-only in the EJB. If anything is altered from
inside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container.The pass-by-reference
can be used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass an
HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented
design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-
end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the
whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value
object (or structure) that holds all the data you need to pass back and forth between front-end/back-end.
Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction
will be flexible enough to support it.

- 88 -
Core Java
12 . The EJB container implements the EJBHome and EJBObject classes. For every request from a
unique client, does the container create a separate instance of the generated EJBHome and
EJBObject classes?
The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference
irrespective of the client request. while refering the EJB Object classes the container creates a separate
instance for each client request. The instance pool maintenance is up to the implementation of the container.
If the container provides one, it is available otherwise it is not mandatory for the provider to implement it.
Having said that, yes most of the container providers implement the pooling functionality to increase the
performance of the application server. The way it is implemented is, again, up to the implementer.
13 . What is the advantage of using Entity bean for database operations, over directly using JDBC
API to do database operations? When would I use one over the other?
Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There
are two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean -
Whenever the instance of the bean is created the container automatically retrieves the data from the
DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For
this the developer needs to map the fields in the database to the variables in deployment descriptor files
(which varies for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make
connection, retrive values, assign them to the objects in the ejbLoad() which will be called by the container
when it instatiates a bean object. Similarly in the ejbStore() the container saves the object values back the
the persistance storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container.
Apart from this, when you use Entity beans you dont need to worry about database transaction handling,
database connection pooling etc. which are taken care by the ejb container.
14 . What is EJB QL?
EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent
objects defined by means of container managed persistence
15 . How can I call one EJB from inside of another EJB?
EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then
acquire an instance reference, and so forth.
16 . What is an EJB Context?
EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container
contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called
SessionContext. These EJBContext objects provide the bean class with information about its container, the
client using the bean and the bean itself
17 . What is an EJB Context?
EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container
contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called
SessionContext. These EJBContext objects provide the bean class with information about its container, the
client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for
more details.
18 . Is method overloading allowed in EJB?
Yes you can overload methods
19 . Should synchronization primitives be used on bean methods?
No. The EJB specification specifically states that the enterprise bean is not allowed to use thread primitives.
The container is responsible for managing concurrent access to beans at runtime.
20. Are we allowed to change the transaction isolation property in middle of a transaction?
No. You cannot change the transaction isolation level in the middle of transaction.

- 89 -

Você também pode gostar