Java Interview
Java Interview
interview questions
1. What is garbage collection? What is the process that is responsible for doing
that in java? - Reclaiming the unused memory by the invalid objects. Garbage
collector is responsible for this process
2. What kind of thread is the Garbage collector thread? - It is a daemon thread.
3. What is a daemon thread? - These are the threads which can run without user
intervention. The JVM can exit when there are daemon thread by killing them
abruptly.
4. How will you invoke any external process in Java? -
Runtime.getRuntime().exec(….)
5. What is the finalize method do? - Before the invalid objects get garbage
collected, the JVM give the user a chance to clean up some resources before it got
garbage collected.
6. What is mutable object and immutable object? - If a object value is changeable
then we can call it as Mutable object. (Ex., StringBuffer, …) If you are not
allowed to change the value of an object, it is immutable object. (Ex., String,
Integer, Float, …)
7. What is the basic difference between string and stringbuffer object? - String
is an immutable object. StringBuffer is a mutable object.
8. What is the purpose of Void class? - The Void class is an uninstantiable
placeholder class to hold a reference to the Class object representing the primitive
Java type void.
9. What is reflection? - Reflection allows programmatic access to information
about the fields, methods and constructors of loaded classes, and the use reflected
fields, methods, and constructors to operate on their underlying counterparts on
objects, within security restrictions.
10. What is the base class for Error and Exception? - Throwable
11. What is the byte range? -128 to 127
12. What is the implementation of destroy method in java.. is it native or java
code? - This method is not implemented.
13. What is a package? - To group set of classes into a single unit is known as
packaging. Packages provides wide namespace ability.
14. What are the approaches that you will follow for making a program very
efficient? - By avoiding too much of static methods avoiding the excessive and
unnecessary use of synchronized methods Selection of related classes based on
the application (meaning synchronized classes for multiuser and non-
synchronized classes for single user) Usage of appropriate design patterns Using
cache methodologies for remote invocations Avoiding creation of variables within
a loop and lot more.
15. What is a DatabaseMetaData? - Comprehensive information about the database
as a whole.
16. What is Locale? - A Locale object represents a specific geographical, political, or
cultural region
17. How will you load a specific locale? - Using ResourceBundle.getBundle(…);
18. What is JIT and its use? - Really, just a very fast compiler… In this incarnation,
pretty much a one-pass compiler – no offline computations. So you can’t look at
the whole method, rank the expressions according to which ones are re-used the
most, and then generate code. In theory terms, it’s an on-line problem.
19. Is JVM a compiler or an interpreter? - Interpreter
20. When you think about optimization, what is the best way to findout the
time/memory consuming process? - Using profiler
21. What is the purpose of assert keyword used in JDK1.4.x? - In order to validate
certain expressions. It effectively replaces the if block and automatically throws
the AssertionError on failure. This keyword should be used for the critical
arguments. Meaning, without that the method does nothing.
22. How will you get the platform dependent values like line separator, path
separator, etc., ? - Using Sytem.getProperty(…) (line.separator, path.separator,
…)
23. What is skeleton and stub? what is the purpose of those? - Stub is a client side
representation of the server, which takes care of communicating with the remote
server. Skeleton is the server side representation. But that is no more in use… it is
deprecated long before in JDK.
24. What is the final keyword denotes? - final keyword denotes that it is the final
implementation for that method or variable or class. You can’t override that
method/variable/class any more.
25. What is the significance of ListIterator? - You can iterate back and forth.
26. What is the major difference between LinkedList and ArrayList? -
LinkedList are meant for sequential accessing. ArrayList are meant for random
accessing.
27. What is nested class? - If all the methods of a inner class is static then it is a
nested class.
28. What is inner class? - If the methods of the inner class can only be accessed via
the instance of the inner class, then it is called inner class.
29. What is composition? - Holding the reference of the other class within some
other class is known as composition.
30. What is aggregation? - It is a special type of composition. If you expose all the
methods of a composite class and route the method call to the composite method
through its reference, then it is called aggregation.
31. What are the methods in Object? - clone, equals, wait, finalize, getClass,
hashCode, notify, notifyAll, toString
32. Can you instantiate the Math class? - You can’t instantiate the math class. All
the methods in this class are static. And the constructor is not public.
33. What is singleton? - It is one of the design pattern. This falls in the creational
pattern of the design pattern. There will be only one instance for that entire JVM.
You can achieve this by having the private constructor in the class. For eg., public
class Singleton { private static final Singleton s = new Singleton(); private
Singleton() { } public static Singleton getInstance() { return s; } // all non static
methods … }
34. What is DriverManager? - The basic service to manage set of JDBC drivers.
35. What is Class.forName() does and how it is useful? - It loads the class into the
ClassLoader. It returns the Class. Using that you can get the instance ( “class-
instance".newInstance() ).
36. Inq adds a question: Expain the reason for each keyword of
1. What gives Java its “write once and run anywhere” nature? - Java is
compiled to be a byte code which is the intermediate language between source
code and machine code. This byte code is not platorm specific and hence can be
fed to any platform. After being fed to the JVM, which is specific to a particular
operating system, the code platform specific machine code is generated thus
making java platform independent.
2. What are the four corner stones of OOP? - Abstraction, Encapsulation,
Polymorphism and Inheritance.
3. Difference between a Class and an Object? - A class is a definition or prototype
whereas an object is an instance or living representation of the prototype.
4. What is the difference between method overriding and overloading? -
Overriding is a method with the same name and arguments as in a parent, whereas
overloading is the same method name but different arguments.
5. What is a “stateless” protocol? - Without getting into lengthy debates, it is
generally accepted that protocols like HTTP are stateless i.e. there is no retention
of state between a transaction which is a single request response combination.
6. What is constructor chaining and how is it achieved in Java? - A child object
constructor always first needs to construct its parent (which in turn calls its parent
constructor.). In Java it is done via an implicit call to the no-args constructor as
the first statement.
7. What is passed by ref and what by value? - All Java method arguments are
passed by value. However, Java does manipulate objects by reference, and all
object variables themselves are references
8. Can RMI and Corba based applications interact? - Yes they can. RMI is
available with IIOP as the transport protocol instead of JRMP.
9. You can create a String object as String str = “abc"; Why cant a button
object be created as Button bt = “abc";? Explain - The main reason you cannot
create a button by Button bt1= “abc"; is because “abc” is a literal string
(something slightly different than a String object, by the way) and bt1 is a Button
object. The only object in Java that can be assigned a literal String is
java.lang.String. Important to note that you are NOT calling a java.lang.String
constuctor when you type String s = “abc";
10. What does the “abstract” keyword mean in front of a method? A class? -
Abstract keyword declares either a method or a class. If a method has a abstract
keyword in front of it,it is called abstract method.Abstract method hs no body.It
has only arguments and return type.Abstract methods act as placeholder methods
that are implemented in the subclasses. Abstract classes can’t be instantiated.If a
class is declared as abstract,no objects of that class can be created.If a class
contains any abstract method it must be declared as abstract.
11. How many methods do u implement if implement the Serializable Interface?
- The Serializable interface is just a “marker” interface, with no methods of its
own to implement. Other ‘marker’ interfaces are
12. java.rmi.Remote
13. java.util.EventListener
14. What are the practical benefits, if any, of importing a specific class rather
than an entire package (e.g. import java.net.* versus import
java.net.Socket)? - It makes no difference in the generated class files since only
the classes that are actually used are referenced by the generated class file. There
is another practical benefit to importing single classes, and this arises when two
(or more) packages have classes with the same name. Take java.util.Timer and
javax.swing.Timer, for example. If I import java.util.* and javax.swing.* and then
try to use “Timer", I get an error while compiling (the class name is ambiguous
between both packages). Let’s say what you really wanted was the
javax.swing.Timer class, and the only classes you plan on using in java.util are
Collection and HashMap. In this case, some people will prefer to import
java.util.Collection and import java.util.HashMap instead of importing java.util.*.
This will now allow them to use Timer, Collection, HashMap, and other
javax.swing classes without using fully qualified class names in.
15. What is the difference between logical data independence and physical data
independence? - Logical Data Independence - meaning immunity of external
schemas to changeds in conceptual schema. Physical Data Independence -
meaning immunity of conceptual schema to changes in the internal schema.
16. What is a user-defined exception? - Apart from the exceptions already defined
in Java package libraries, user can define his own exception classes by extending
Exception class.
17. Describe the visitor design pattern? - Represents an operation to be performed
on the elements of an object structure. Visitor lets you define a new operation
without changing the classes of the elements on which it operates. The root of a
class hierarchy defines an abstract method to accept a visitor. Subclasses
implement this method with visitor.visit(this). The Visitor interface has visit
methods for all subclasses of the baseclass in the hierarchy.
1. What are the implicit objects? - Implicit objects are objects that are created by
the web container and contain information related to a particular request, page, or
application. They are: request, response, pageContext, session, application, out,
config, page, exception.
2. Is JSP technology extensible? - Yes. JSP technology is extensible through the
development of custom actions, or tags, which are encapsulated in tag libraries.
3. 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
4. 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.
5. 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 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
%>
6. 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:
7. <%-- the scriptlet is now commented out
8. <%
9. out.println("Hello World");
10. %>
11. --%>
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
**/
%>
12. 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 <HTML
Tag><Some Headers><Body>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
13. 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.
14. <jsp:useBean id="foo" class="com.Bar.Foo" >
15. <jsp:setProperty name="foo" property="today"
16. value="<%=java.text.DateFormat.getDateInstance().format(new
java.util.Date()) %>"/ >
17. <%-- scriptlets calling bean setter methods go here --%>
18. </jsp:useBean >
19. How can I enable session tracking for JSP pages if the browser has disabled
cookies? - We know that session tracking uses cookies by default to associate a
session identifier with a unique user. If the browser does not support cookies, or if
cookies are disabled, you can still enable session tracking using URL rewriting.
URL rewriting essentially includes the session ID within the link itself as a
name/value pair. However, for this to be effective, you need to append the session
ID for each and every link that is part of your servlet response. Adding the session
ID to a link is greatly simplified by means of of a couple of methods:
response.encodeURL() associates a session ID with a given URL, and if you are
using redirection, response.encodeRedirectURL() can be used by giving the
redirected URL as input. Both encodeURL() and encodeRedirectedURL() first
determine whether cookies are supported by the browser; if so, the input URL is
returned unchanged since the session ID will be persisted as a cookie. Consider
the following example, in which two JSP files, say hello1.jsp and hello2.jsp,
interact with each other. Basically, we create a new session within hello1.jsp and
place an object within this session. The user can then traverse to hello2.jsp by
clicking on the link present within the page.Within hello2.jsp, we simply extract
the object that was earlier placed in the session and display its contents. Notice
that we invoke the encodeURL() within hello1.jsp on the link used to invoke
hello2.jsp; if cookies are disabled, the session ID is automatically appended to the
URL, allowing hello2.jsp to still retrieve the session object. Try this example first
with cookies enabled. Then disable cookie support, restart the brower, and try
again. Each time you should see the maintenance of the session across pages. Do
note that to get this example to work with cookies disabled at the browser, your
JSP engine has to support URL rewriting.
20. hello1.jsp
21. <%@ page session="true" %>
22. <%
23. Integer num = new Integer(100);
24. session.putValue("num",num);
25. String url =response.encodeURL("hello2.jsp");
26. %>
27. <a href='<%=url%>'>hello2.jsp</a>
28. hello2.jsp
29. <%@ page session="true" %>
30. <%
31. Integer i= (Integer )session.getValue("num");
32. out.println("Num value in session is "+i.intValue());
33. How can I declare methods within my JSP page? - You can declare methods
for use within your JSP page as declarations. The methods can then be invoked
within any other methods you declare, or within JSP scriptlets and expressions.
Do note that you do not have direct access to any of the JSP implicit objects like
request, response, session and so forth from within JSP methods. However, you
should be able to pass any of the implicit JSP variables as parameters to the
methods you declare. For example:
34. <%!
35. public String whereFrom(HttpServletRequest req) {
36. HttpSession ses = req.getSession();
37. ...
38. return req.getRemoteHost();
39. }
40. %>
41. <%
42. out.print("Hi there, I see that you are coming in from ");
43. %>
44. <%= whereFrom(request) %>
45. Another Example
46. file1.jsp:
47. <%@page contentType="text/html"%>
48. <%!
49. public void test(JspWriter writer) throws IOException{
50. writer.println("Hello!");
51. }
52. %>
53. file2.jsp
54. <%@include file="file1.jsp"%>
55. <html>
56. <body>
57. <%test(out);% >
58. </body>
59. </html>
60. 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:
61. <%
62. session.setMaxInactiveInterval(300);
63. %>
would reset the inactivity period for this session to 5 minutes. The inactivity
interval is set in seconds.
64. 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:
65. <%
66. //creating a cookie
67. Cookie mycookie = new Cookie("aName","aValue");
68. response.addCookie(mycookie);
69. //delete a cookie
70. Cookie killMyCookie = new Cookie("mycookie", null);
71. killMyCookie.setMaxAge(0);
72. killMyCookie.setPath("/");
73. response.addCookie(killMyCookie);
74. %>
75. 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.
76. public void doPost (HttpServletRequest request, HttpServletResponse
response) {
77. try {
78. govi.FormBean f = new govi.FormBean();
79. String id = request.getParameter("id");
80. f.setName(request.getParameter("name"));
81. f.setAddr(request.getParameter("addr"));
82. f.setAge(request.getParameter("age"));
83. //use the id to compute
84. //additional bean properties like info
85. //maybe perform a db query, etc.
86. // . . .
87. f.setPersonalizationInfo(info);
88. request.setAttribute("fBean",f);
89. getServletConfig().getServletContext().getRequestDispatcher
90. ("/jsp/Bean1.jsp").forward(request, response);
91. } catch (Exception ex) {
92. . . .
93. }
94. }
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" /
95. 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:
o The service() method has to invoke the _jspService() method
o The init() method has to invoke the jspInit() method
o 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" %>
96. 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
97. <%!
98. String blanknull(String s) {
99. return (s == null) ? "" : s;
100. }
101. %>
102. then use it inside your JSP form, like
103. <input type="text" name="shoesize" value="<%=blanknull(shoesize)% >"
>
104.How can I get to print the stacktrace for an exception occuring within my
JSP page? - By printing out the exception’s 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:
105. <%@ page isErrorPage="true" %>
106. <%
107. out.println(" ");
108. PrintWriter pw = response.getWriter();
109. exception.printStackTrace(pw);
110. out.println(" ");
111. %>
112.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.
113. <%@ page import="java.util.*" %>
114. <%!
115. ServletConfig cfg =null;
116. public void jspInit(){
117. ServletConfig cfg=getServletConfig();
118. for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) {
119. String name=(String)e.nextElement();
120. String value = cfg.getInitParameter(name);
121. System.out.println(name+"="+value);
122. }
123. }
124. %>
125.How can my JSP page communicate with an EJB Session Bean? - The
following is a code snippet that demonstrates how a JSP page can interact with an
EJB session bean:
126. <%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
127. <%!
128. //declare a "global" reference to an instance of the home interface of the
session bean
129. AccountHome accHome=null;
130. public void jspInit() {
131. //obtain an instance of the home interface
132. InitialContext cntxt = new InitialContext( );
133. Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
134. accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
135. }
136. %>
137. <%
138. //instantiate the session bean
139. Account acct = accHome.create();
140. //invoke the remote methods
141. acct.doWhatever(...);
142. // etc etc...
143. %>
J2EE interview questions
o Applets
o Application clients
o Java Web Start-enabled rich clients, powered by Java Web Start
technology.
o Wireless clients, based on Mobile Information Device Profile (MIDP)
technology.
try
{
//some statements
}
catch
{
// statements when exception is cought
}
finally
{
//statements executed whether exception occurs or
not
}
32. What is the Locale class? The Locale class is used to tailor program output to
the conventions of a particular geographic, political, or cultural region.
33. What must a class do to implement an interface? It must provide all of the
methods in the interface and identify the interface in its implements clause.