Enter your keyword


JAVA Interview Questions-1

1.What is a transient variable ?
Ans: A transient variable is a variable which may not be either serialized or deserialized i.e neither saved nor restored during the process of serialization.

if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can’t be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

2.What is a exception?
Ans: When a program violates the semantic constraints of the java programming language , the java virtual machine
sends this signal to the program as an exception.
An exception can be defined as an abnormal event which occurs during the execution of a program and disrupts the normal flow of the program’s instructions.

3.What are checked and unchecked exceptions?

Ans:1.Checked exceptions represent invalid conditions in areas outside the immediate control of the program like database
problems , network outages and absent files.
2.A checked exception is any subclass of Exception excluding class RuntimeException and its subclasses.
3.A method is obliged to establish a policy for all checked exceptions thrown by its implementation. The compiler forces programmers to handle these exceptions either by try catch or using throws clause.
4.These are the exceptions that should be handled at compile time otherwise we will get compile time errors.

4.Examples of Checked Excptions are IOException,InterruptedException,CloneNotSupportedException,ClassNotFoundException?
Ans:1.Unchecked exceptions reflect errors in the program logic
that cannot be reasonably recovered from at runtime like
invalid arguments passed to a non private method.
2.Unchecked exceptions are class RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked.
3.They donot have to be explicitly caught i.e methods are not obliged to establish a policy for unchecked exceptions thrown by its implementation.
4.There is no such restrictions for unchecked exceptions , Infact programmers may not even know that the exception could be thrown.

5.Examples of Unchecked Exceptions:
ClassCastException,IllegalArgumentException,IllegalStateExceptiDifference between ArrayList and Vector
1.ArrayList is not synchronized whereas vector is.
Methods in Vector are Synchronized which means they are thread safe and thus prelude access to the vector elements by concurrent threads. But this imposes additional overhead on the JVM as it has to acquire and release locks on vector objects under consideration. For this reason Vector is bad in performance and ArrayList are good .
2.ArrayList has no default size where as Vector has a default size of 10.
3.Vector is a old collection came with jdk1.0 or later so it Comes under legacy classes.Where as ArrayList was introduced
In java 1.2
4.ArrayList will grow half the size what you initialize , where as vector will grow double the initial size
5.When to use Vector ?
Use Vector only if it will be accessed by multiple threads at a time else ArrayList is always a better option.
6.What is a class?
Class is a blue print for an object which defines the functionality of an object.

7.How many ways we can create object ?
Ans:We can create an object using 4 ways they are:
1.using new operator.
This is the most common way to create an object in way.
MyObject object = new MyObject();
2.using object deserialization
Object deserialization is nothing but creating an object from
its serialized form
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(“abc.txt”));
MyObject object = (MyObject)ois.readObject();
3.using cloning technique
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object= anotherObject.clone();
If we know the name of the class and if it has a public default constructor we can create an object in this way
MyObject object = (MyObject)Class.forName(“MyObject”).newInstance();

8.What is singleton design pattern?
Ans:Singleton design pattern ensures that there exists only one instance of the class at any time.
The sole purpose of such a class is to ensure that only one
instance of the class is created for the entire application
and that instance is shared across multiple clients

Step1. Provide a default constructor

public class SingletonConnectionObject
private SingletonConnectionObject()

Step2. Create a method for getting the reference to the singleton object

public class SingletonConnectionObject {

private SingletonConnectionObject()

private static Connection connection = null;

catch(Exception e)


public static Connection getConnection()

return connection;

9. Can we declare a class as private?
Ans:Outer class can’t be declared as private but inner classes can.

10.What is overriding and overloading ?
Ans:When a class defines a method using the same name , return type and arguments but with different behaviour as a method in its superclass , the method in the class overrides the method in the superclass.
Overloading is when a class defines a method using the same name but either with different type of arguments or different number of arguments and with same or different return type as a method available in same class or super class.

11.How you declare error page by using page directive?
Ans:You can use the errorPage attribute of page directive to have an uncaught run-time exceptions automatically forwarded to an error processing page.
<%@ page errorPage=”error.jsp“ %>
It automatically redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.Within error.jsp you indicate that it is an error processing page via isErrorPage attribute of the page directive

<%@ page isErrorPage=”true”%>
The Throwable object describing the exception may be accessed within the error page via the exception implicit object.
errorPage :- Defines a URL to the resource to which uncaught Throwables should be sent.
isErrorPage:- Defines whether the current page represents another JSP’s error page.The default value is “false” but if it is true , the page has access to the implicit exception object .If false , the implicit exception
object is not available to the JSP.

12.How many types of JSP elements are there in java?Explain briefly
Ans:template text : Everything in the page that is not a jsp is template text is sent to the browser as is.
scripting elements
standard and custom actions
expression language elements
Directives: A directive is a way for programmers to give special instruction to the container at page translation time. Using directive tag user can import packages , define error handling pages etc.
There are three types of directives available : page , include and taglib.

13. What are implicit objects in jsp?
Ans: Implicit objects are the objects that are created by the web-container and contain information related to a particular request,page or application.
There are 9 implicit objects.

a) request b) response c) out d) session e) config f) application g) page h) pageContext i)exception

14. What is the interface the servlet implements for thread safety?

15. Explain RequestDispatcher?
Ans: Its an interface. Defines an object that receives requests from the client and sends them to any resource such as servlet,HTML file or JSP file on the server.
RequestDispatcher interface defines two methods:

void forward(ServletRequset request,ServletResponse response)

forwards a request from a servlet to another resource (servlet,JSP file or HTML file) on the server.

void include(ServletRequest request,ServletResponse response)
includes the content of a resource (servlet,JSP file or HTML file) in the response.

16.In how many ways RequestDispatcher can be obtained ?

Ans:RequestDispatcher object can be obtained in three ways.

1.With the help of ServletRequest object

ServletRequest.getRequestDispatcher(String path)

2.With the help of ServletContext object

ServletContext.getRequestDispatcher(String path)
ServletContext.getNamedDispatcher(String names)
17.Is servlet thread safe?
Ans:Servlet is not thread safe by itself.

18.Write the System Date Expression in JSP?

Ans: <%@ page import=”java.util.Date” %>
<%=new Date() %>

19. What is JSP ? Is JSP Thread safe?
Ans:Java Server Pages is a server side programming technology that enables the creation of dynamic web pages and applications.This is accomplished by embedding java code into HTML , DHTML or other document types. Yes , Page directive has got isThreadSafe attribute .

isThreadSafe: Defines wheteher the generated servlet needs to implement the SingleThreadModel

Its default value is true which implies the generated
Servlet is thread safe.

20. Difference between <%@ include file=”” %> and or static or dynamic include?
Ans:1.include directive will merge the content of included jsp with including jsp at compile time and creates a single servlet so there is a possibility that size of the file becomes large.
2. include directive inserts the source from the value of the file attribute to the current page at translation time where as include action includes the response from the value of the page attribute to the current page at request or run time.
3. include directive is used to include static resources whereas include action is used to include dynamic content or static content .
4. include directive is evaluated only once at translation time whereas include action is evaluated with every request.

21. When to use include directive and when to use include action ?
Ans:Use include directive if the resource is not going to change frequently.
Use include action if the resource changes frequently or is dynamic.

22. Difference between Set and List ?

Ans:1.All of the List implemented classes maintain insertion order where as Set implemented classes do not maintain insertion order.
2.As set cares about uniqueness set doesn’t allow duplicates whereas List allows duplicates.

23. What is the difference between process and thread ?

Ans:Process is a program in execution whereas thread is a separate path of execution in program.

24. How do u pass data from one jsp to another jsp?

Ans:You can pass parameter names and values to the target file by using a clause.

25. Difference between Hashtable and HashMap ?

Ans:1.HashMap permits null values in the form of both key and values whereas Hashtable doesn’t permit null values in any form.
2.HashMap is not synchronized whereas Hashtable is.
Methods in Hashtable are Synchronized which means they are thread safe and thus prelude access to the hashtable elements by concurrent threads. But this imposes additional overhead on the JVM as it has to acquire and release locks on hashtable objects under consideration. For this reason Hashtable is bad in performance and HashMap are good .
3.Hashtable is a old collection came with jdk1.0 or later so it comes under legacy classes.Where as HashMap was introduced
In java 1.2.

26.From which version of java Autoboxing concept is introduced ?
Ans:Java 1.5

27.Can a try exist with multiple catch blocks?
Ans:Yes. But the order of Exception should be up the hierarchy.

28.Can a try exist without a catch block ?
Ans:Yes but with finally.

29.I have an ArrayList containing duplicate elements.How to remove those duplicate elements and get only unique elements ?
Ans:List listOfDuplicates = new ArrayList();
Set uniqueSet = new HashSet(listOfDuplicates) will remove all duplicates from the list
28. How to remove an element from an ArrayList?
Ans:remove(int index) – returns the element previously at the specified position
remove(Object o) – true if this list contained the specified element.

30. What does Class.forName do?

Ans:A call to Class.forName(“x”) causes the class named x to be dynamically loaded at runtime if not already noted.

31.How to loop through a Map?

Ans:There is no simple API to loop through all the items in Map.
Map testMap = new HashMap();
Iterator iterator = testMap.keySet().iterator();
String key=it.next();

<%@ taglib uri=” http://java.sun.com/jsp/jstl/core” prefix=”c” %>

32.How to read input from console?

Ans: BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));
try {
String username = buffReader.readLine();
System.out.println(“….name of the user is..”+username);
} catch (IOException e) {
// TODO Auto-generated catch block

//In java5

Scanner scan = new Scanner(System.in);
String name=scan.nextLine();
System.out.println(“….name of the user is..”+name);

// In java6

Console console = System.console();
username=console.readLine(“Please eneter user name”);

33.How to convert a given array to a list in Java?

How do I convert array to collection ?

Ans:The java.util.Arrays class contains various methods for manipulating arrays(such as searching and sorting)

Integer[] integerArray = {10,20,30};
List list = Arrays.asList(integerArray);

34.What method should the key class of HashMap override ?

The methods to override are hashCode() and equals().

35.What is the difference between Enumeration and iterator ?

1. The functionality of Enumeration interface is duplicated by the Iteartor interface.
2. Enumeration acts as read only interface , because it has the methods namely hasMoreElements() and nextElement() only to traverse and fetch the objects where as Iterator has an extra method called remove() in addition to hasNext() and next() which allows the caller to remove elements from the underlying collection during the iteration.
3. Enumeration comes under under legacy interfaces as it came with jdk 1.0 where as Iterator was introduced in java1.2

36.Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
Ans: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 updation of the links at the point of insertion.Therefore , the LinkedList allows for fast insertions and deletion.

37. Can we insert duplicate elements into Hashset ? What is the output when duplicate elements are inserted with example ?
Ans:As set cares about uniqueness we cannot insert duplicate elements into HashSet. If the set already contains the specified element the call leaves the set unchanged and returns false.

38. What is Autoboxing ?
Ans:Introduced in java5 , is the automatic conversion the java compiler makes between the primitive (basic) types and their corresponding object wrapper classes

39 . Difference between daemon thread and normal thread? Give an example of daemon thread ?

Daemon threads are created by the JVM unlike normal threads which are created by the user.
The Daemon threads provide services to the user created threads and they run in background.
To set them you have to write
and to check whether a thread is a daemon thread or not you write

garbage collection is a daemon thread.

In java we have two types of Threads: Daemon Thread and User Threads.
Generally all threads created by the programmer are user thread.
User thread are generally meant to run our program code.JVM doesn’t terminates unless all the user thread

On the other hand we have daemon threads.Typically these threads are service provider threads.They should not be used to run your program code but some system code.These threads run parallely to your code but survive on the mercy of the JVM.When JVM finds no user threads it stops and all daemon threads terminate instantly.Thus one should never rely on daemon thread to run any program code.

Garbage collector runs as a daemon thread to reclaim any unused memory.When all threads terminates , JVM may stop and garbage collector also terminates instantly.

1.Daemon threads are created by the JVM unlike user/normal threads which are created by the programmers.

2.JVM doesn’t terminates until all the user threads terminate where as daemon threads survive on the mercy of JVM.

3.User threads are generally meant to run program code . Daemon threads should not be used to run program code but some system code. The Daemon threads provide services to the user created threads and they run parallely to program code in the background .
39. How to sort an array.

int[] intArray = {10,20,30,40,50};
// ensure array sorted

40.How to search for an element in the array ?

Ans:int[] intArray = {10,20,30,40,50};
int search=Arrays.binarySearch(intArray,20);

41. How to compare if two arrays are equal?

Ans:int[] intArray1={10,20,30};
int[] intArray2={10,20,30};

42. How to get maximum and minimum number in an array?
Ans:Integer[] intArray = {10,20,30,40,50,60};
int maxNumber = Collections.max(Arrays.asList(intArray));
int minNumber = Collections.min(Arrays.asList(intArray));

43.How to get synchronized List,Set and Map?
Ans:List notSyncList = new ArrayList();
List synchronizedList = Collections.synchronizedList(notSync);

Set notSyncSet = new HashSet();
Set synchronizedList = Collections.synchronizedSet(notSync);

Set notSyncMap = new HashMap();
Set synchronizedList = Collections.synchronizedMap(notSyncMap);

44. How to empty a List,Set and Map?
Ans:List list = new ArrayList();

Set set = new HashSet();

Map map = new HashMap();

System.out.println(“….size of list before eptying……..”+list.size());
System.out.println(“….size of set before eptying……..”+set.size());
System.out.println(“….size of map before eptying……..”+map.size());

System.out.println(“….size of list after eptying……..”+list.size());
System.out.println(“….size of set after eptying……..”+set.size());
System.out.println(“….size of map after eptying……..”+map.size());

45. How to copy elements from one list to another list?

Ans: List listOne = new ArrayList();

List listTwo = new ArrayList();


for(Integer element : listOne)

46.How to create an array containing the elements in a set?

Ans: Set set = new HashSet();

String[] namesArray = (String[])set.toArray(new String[set.size()]);

47.What is a List,Set and Map interface?

Ans:List: The list interface provides support for ordered collection of objects.The user of the interface has precise control over where in the list each element is inserted and can access elements by their integer index.

Set : An interface which contains only unique elements and avoids duplicate elements.

Map: A map stores the elements in the form of key value pairs.

48. Difference between constructor and method ?

Ans:Constructor gets called automatically by the JVM when an object is created but method needs to be called explicitly.

Constructor cannot have return types where as Methods have return types.

49. Can static methods be overridden ?
Ans: No . If a subclass defines a static method with the same signature as a static method in the superclass the method in the subclass hides the one in the superclass.

50. Why does TreeSet.add throws ClassCastException?

Ans: Class MyClass
int i;
MyClass(int i)
Set set = new TreeSet();
set.add(new MyClass(10));
set.add(new MyClass(20)); // throws a ClassCastException

The TreeSet constructor says: constructs a new empty set , sorted according to the elements natural ordering.
All elements inserted into the set must implement the Comparable interface .
Furthermore all such elements must be mutually comparable e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set.

51. What is instanceof ?
Ans:The instanceof operator is used to check whether the runtime type of an object is compatible with a given type.

52. Difference between ServletContext and ServletConfig ?

Ans: 1. ServletConfig is associated with servlet whereas ServletContext is associated with the entire web-application.
2. Container creates an object of ServletConfig for each servlet , where as container creates only single object of ServletContext for a web application.
3. ServletConfig gets destroyed just before servlet- deinstantiation where as ServletContext gets destroyed when we undeploy the web application from the container.

53.Can an overriding method have a different return type than the overridden method ?

Ans:Before java5.0 when a class overrides a method with the same signature as a method in the superclass both parameters and return type must match exactly.
But with the release of java5.0 covariant return type were introduced . So you can override a method with the same signature but can return a subclass of the object returned in the superclass
In another words a method in the subclass can return an object type whose type is a subclass of the type returned by the method with the same signature in the superclass.

54.Explain JSP life cycle ?

Ans:1.The container reads the “web.xml” for the application but doesn’t do anything else with the .jsp file until the first time it is required.
2.The container tries to translate the .jsp into .java source code for a servlet class.
3.The container tries to compile the .java source into a .class file.
4.The container loads the newly generated servlet class.
5.The container instantiates the servlet and causes the servlet’s jspInit() method to run.
6.The container creates a new thread to handle this client’s request and the servlet’s _jspService() method runs

55.Difference between Abstract classes and interfaces?

Ans:1.In addition to abstract methods an abstract class can also contain concrete methods whereas all methods in an interface are implicitly abstract.

2.In addition to static variables abstract classes can have instance variables where as all variables in an interface are implicitly static and final.

3. Access modifies like public,protected and default can be applied to methods available in abstract class whereas all methods in an interface are implicitly public.

4.Abstract classes can have constructors whereas the same is not true in interfaces.

5.Abstract class cannot support multiple inheritance whereas interfaces support multiple inheritance , thus a class can implement several interfaces but can extend only one abstract class.

56.Difference between forward and include

Ans:When we use RequestDispatcher’s include method() we get the combined output generated both by calling and called servlet whereas with forward() we get output from only called servlet.

57.Difference between GET and POST?

Ans:1.The total number of characters in a GET is limited say for example if the user types a long passage into a search input box the GET request might not work ,where as there is no such restriction in POST requests and can be used to send unlimited data .
2.The data you send with the GET is appended to the URL up in the browser bar , so whatever you send is exposed and hence cannot be used to send sensitive data whereas POST request includes form data in the body of the request and hence can be used to send confidential data like passwords.
3.GET requests are idempotent.They should be able to run multiple requests without causing any unwanted side effects on the server. So they are considered as read only request and can be used for retrieval of data. Where as POST requests are non idempotent that’s why they are considered as update requests.
4.doGet() is invoked in response to HTTP GET request.This happens when user clicks on a link or enters a URL into the browser’s address bar.It also happens with some html forms those with method=”get” specified in form tag. doPost() is called in response to HTTP POST request.This happens with some HTML forms (those with method=”post” specified in the form tag).

58.Difference between request redirect and RequestDispatcher?
Ans:1.A request dispatch happens on the server while a redirect happens on the client.

2.A request dispatch hands over the request to another component on the server usually within the same web application whereas request redirect simply tells the browser to go to a different URL.

3.In request dispatch the user never knows someone else took over the control because the URL in the browser doesn’t change where as in redirect the user sees the new URL in the browser.

4.In request dispatch , the dispatched JSP executes against the same request and response objects within the same thread.

59.How to pass control from one jsp page to another?
Ans:We can pass control from first jsp to second by using

60.How can a servlet call a JSP error page?
Ans:The servlet needs to forward the request to the specific
error page URL
RequestDispatcher rd = request.getRequestDispatcher(“relative path of the error.jsp file”);

61.How many instances will be created for a servlet?
Ans:if thousand users access a servlet.Only one instance , since servlet is multithreaded
So only one instance will be created.

62.How does a servlet communicate with a JSP page?
Ans:A servlet can communicate with JSP by using the RequestDispatcher mechanism
RequestDispatcher rd1 = request.getRequestDispatcher(“path of the jsp file”);
RequestDispatcher rd2 = context.getRequestDispatcher(“path of the jsp file”);
RequestDispatcher rd3 = context.getNamedDispatcher(“name of the servlet”)

63.Why there is no constructors in servlets ? can we have constructors in servlets . If we can how is differed from
init() method in servlets?
Ans:At any time there will be only one instance of the servlet
running so there is no need of constructors.For passing any
values to a servlet on creation you can add parameters to deployment descriptor file and for performing any tasks on initializing the servlet you can perform them in servlet init().So there is no need for constructors .

64.How to sort a List ?

Ans:List list = new ArrayList();

65.How to sort a Set?
Ans:Set set = new HashSet();
SortedSet sortedSet = new TreeSet(set);

66.How to sort a Map?

Ans:Map map = new HashMap();

SortedMap sortedMap = new TreeMap(map);

64. How to implement Connection pooling ?


public class ConnectionPoolingThroughDataSource {

private static Connection conn = null;
public static Connection getConnection()

InitialContext ctx;
DataSource ds = null;
try {
ctx = new InitialContext();
ds = (DataSource)ctx.lookup(“java:/jdbc/jndiName”);
conn= ds.getConnection();
} catch (NamingException e){
} catch (SQLException e) {

return conn;



jdbc/jndiName is what you should specify in mysql-ds.xml file .

mysql-connector-java-5.1.6 jar should be kept in C:\Program Files\jboss-4.0.5.GA\server\default\lib

65. When you declare a method as abstract method?
Ans:When we want to design such a method which is different for every of its child class , means all the subclass has that method but with different behaviour , then we declare the method as abstract.

66.How to reverse a String ?

Ans: String s = “lavanya”;
StringBuffer sb = new StringBuffer(s);
System.out.println(“ reversed string is ”+sb.reverse().toString());

67. How will you override default serialization mechanism in java?
Ans:Serializable is a marker interface.But you may wish to control on how an object is serialized instead of using the default mechanism.In such case add implementations of readObject() and writeObject() methods to the class being serialized and override default serialization mechanism
Also instead of using serializable interface , Externalizable interface can be used

68 What is JVM?
Ans:This is the application that executes a java program . Basically it converts byte code into native understandable format or machine code depending on the underlying operating system and hadware combination

69.Can you use two main methods in same class?

Ans:Yes its possible but they should have different parameter list.

No Comments

Add your review

Your email address will not be published.

${entry.key} ${entry.value}