Advanced Java Interview Questions- 4

Advanced Java Interview Questions- 4

1.What is Servlet chaining?

Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.
In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the
last servlet is reached. Its output is then sent back to the client.

2.what is connection pooling?

Class which manages no of user requests for connections to improve the performance.


3.What are the different servers available for developing and deploying Servlets?

a) JRun2.0--Allaire
b) Apache --jserv
c) jwsdk2.0 --sun
d) servletexec
e) Tomcat webserver--tomcat
f)Weblogic AS--BEA Systems
g)NetDynamics5.0--sun
h)Iplanet--sun&netscape
i)Netscape--netscape
g)IBM websphere--IBM
h)oracle--oracle
i)Proton-Pramati technologies

4.How do you handle DataBase access and in which method of the servlet do you like to create connection.
init()

5.If you want to improve the performance how do you create connections for multiple users?

Connection Pooling.

6.How do servlets handle multiple simultaneous requests?
The server has multiple threads that are available to handle requests. When a request comes in, it is
assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the
servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

7.Why should we go for interservlet communication?
Servlets running together in the same server communicate with each other in several ways.
The three major reasons to use interservlet communication are:
a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object)
b) Servlet reuse - allows the servlet to reuse the public methods of another servlet.
c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)

8.Is it possible to call servlet with parameters in the URL?
yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).

9.How are Servlets and JSP Pages related?
jSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.
Servlets:

10.How do servlets handle multiple simultaneous requests?
Using Threads

11.How do I automatically reload servlets?
depends upon the server's servlet reload properites.

12.My servlet, which ran correctly under the Servlet 2.0 APIs (Java Web Server 1.1.3) is not running under the Servlet 2.1 APIs (Java Web Server 2.0). What's wrong?

You might have used servlet to servlet communication by using servletcontext methods like
getServlet(),getServlets() which are depricated and returns null from new release that is from
servlet2.1 API.

13.What are the types of ServletEngines?
Standalone ServletEngine: A standalone engine is a server that includes built-in support for servlets.
Add-on ServletEngine: Its a plug-in to an existing server.It adds servlet support to a server that was not originally designed with servlets in mind.
Embedded ServletEngine: it is a lightweight servlet deployment platform that can be embedded in another application.that application become true server.

14. List out Differences between CGI Perl and Servlet?
Servlet CGI
Platform independent Platform dependent.
Language dependent Language independent.

15.what is httptunneling?
it is mechanism of performing both write and read operations using http protocol.it is extending the functionality of htp protocol.

16.What is a JSP and what is it used for?
Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.

17.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. To use custom JSP tags, you need to define three separate components:
1. the tag handler class that defines the tag\'s behavior
2. the tag library descriptor file that maps the XML element names to the tag implementations
3. the JSP file that uses the tag library
When the first two components are done, you can use the tag by using taglib directive:
<%@ taglib uri="xxx.tld" prefix="..." %>
Then you are ready to use the tags you defined. Let's say the tag prefix is test:
MyJSPTag or
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class.

<%=identifier.getclassField() %>
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.

18.What are the two kinds of comments in JSP and what's the difference between them ?
<%-- JSP Comment --%>
<!-- HTML Comment -->

19.What is JSP technology?
Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.

20.What is JSP page?
A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.

21.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

22.How many JSP scripting elements and what are they?
There are three scripting language elements:
--declarations
--scriptlets
--expressions

23.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.

24.Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

25.Can we use the constructor, instead of init(), to initialize servlet?
Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

26.How can a servlet refresh automatically if some new data has entered the database?
You can use a client-side Refresh or Server Push.

27.What information is needed to create a TCP Socket?
The Local Systems IP Address and Port Number. And the Remote System’s IPAddress and Port Number.

28.What Class.forName will do while loading drivers?
It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

29.The code in a finally clause will never fail to execute, right?
Using System.exit(1); in try block will not allow finally code to execute.

30.How many messaging models do JMS provide for and what are they?
JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

31.How to Retrieve Warnings?
SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
while (warning != null)
{
System.out.println(\"Message: \" + warning.getMessage());
System.out.println(\"SQLState: \" + warning.getSQLState());
System.out.print(\"Vendor error code: \");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}

32.How many JSP scripting elements are there and what are they?
There are three scripting language elements: declarations, scriptlets, expressions.

33.Why does JComponent have add() and remove() methods but Component does not?

because JComponent is a subclass of Container, and can contain other components and jcomponents. How can I implement a thread-safe JSP page? - 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.

34.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.

35.What are stored procedures? How is it useful?
A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements every time a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db’s support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.

36.How do I include static files within a JSP page?

Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request.

37.In the Servlet 2.4 specification SingleThreadModel has been deprecated, why?

Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

38.How do you restrict page errors display in the JSP page?
You first set "Errorpage" attribute of PAGE directory to the name of the error page (ie Errorpage="error.jsp")in your jsp page .Then in the error jsp page set "isErrorpage=TRUE". When an error occur in your jsp page it will automatically call the error page.

39,How does JSP handle run-time exceptions?
You can use the errorPage attribute of the page directive to have uncaught runtime exceptions automatically forwarded to an error processing page.
For example:
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:
the 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.

40.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:
--%>
You can also use HTML-style comments anywhere within your JSP page. These comments are visible at the client. For example:
Of course, you can also use comments supported by your JSP scripting language within your scriptlets.

41.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 serializable. 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-byreference" 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 ejb's 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.

42.How can I implement a thread-safe JSP page?
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.

43.What JSP lifecycle methods can I override?

You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:

44.How do I perform browser redirection from a JSP page?
You can use the response implicit object to redirect the browser to a different resource, as:
response.sendRedirect("http://www.exforsys.com/path/error.html");
You can also physically alter the Location HTTP header attribute, as shown below:
You can also use the:
Also note that you can only use this before any output has been sent to the client. I beleve this is the case with the response.sendRedirect() method as well. If you want to pass any paramateres then you can pass using >

45.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:
Another Example:
file1.jsp:
file2.jsp
<%test(out);% >

46.Can I stop JSP execution while in the midst of processing a request?
Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (assuming Java is your scripting language) is to use the return statement when you want to terminate further processing.

47.Can a JSP page process HTML FORM data?
Yes. However, unlike Servlet, you are not required to implement HTTP-protocol specific methods like doGet() or doPost() within your JSP page. You can obtain the data for the FORM input elements via the request implicit object within a scriptlet or expression as.

48.Is there a way to reference the "this" variable within a JSP page?
Yes, there is. Under JSP 1.0, the page implicit object is equivalent to "this", and returns a reference to the Servlet generated by the JSP page.

49.Can you make use of a ServletOutputStream object from within a JSP page?
No. You are supposed to make use of only a JSPWriter object (given to you in the form of the implicit object out) for replying to clients.
A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(), although from an implementational perspective, it is not.
A page author can always disable the default buffering for any page using a page directive as:

50.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
The is used for including non-JSP files.

51.How do I mix JSP and SSI #include? What is the difference between include directive & jsp:include action?

1. provides the benefits of automatic recompliation,smaller class size ,since the code corresponding to the included page is not present in the servlet for every included jsp page and option of specifying the additional request parameter.
2.The also supports the use of request time attributes values for dynamically specifying included page which directive does not.
3.the include directive can only incorporate contents from a static document.
4. can be used to include dynamically generated output e.g.. from servlets.
5.include directive offers the option of sharing local variables, better run time efficiency.
6.Because the include directive is processed during translation and compilation, it does not impose any restrictions on output buffering.

52.Can a JSP page instantiate a serialized bean?
No problem! The use Bean action specifies the beanName attribute, which can be used for indicating a serialized bean.
For example:
A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INFjspbeans directory for it to be located by the JSP engine.

53.What is JSP?
Let's consider the answer to that from two different perspectives: that of an HTML designer and that of a Java programmer.
If you are an HTML designer, you can look at JSP technology as extending HTML to provide you with the ability to seamlessly embed snippets of Java code within your HTML pages. These bits of Java code generate dynamic content, which is embedded within the other HTML/XML content you author. Even better, JSP technology provides the means by which programmers can create new HTML/XML tags and JavaBeans components, which provide new features for HTML designers without those designers needing to learn how to program.
Note: A common misconception is that Java code embedded in a JSP page is transmitted with the HTML and executed by the user agent (such as a browser). This is not the case. A JSP page is translated into a Java servlet and executed on the server. JSP statements embedded in the JSP page become part of the servlet generated from the JSP page. The resulting servlet is executed on the server. It is never visible to the user agent.
If you are a Java programmer, you can look at JSP technology as a new, higher-level means to writing servlets. Instead of directly writing servlet classes and then emitting HTML from your servlets, you write HTML pages with Java code embedded in them. The JSP environment takes your page and dynamically compiles it. Whenever a user agent requests that page from the Web server, the servlet that was generated from your JSP code is executed, and the results are returned to the user.

54.How do you prevent the Creation of a Session in a JSP Page and why? What is the difference between include directive & jsp:include action?

By default, a JSP page will automatically create a session for the request if one does not exist.
However, sessions consume resources and if it is not necessary to maintain a session, one should not be created. For example, a marketing campaign may suggest the reader visit a web page for more information. If it is anticipated that a lot of traffic will hit that page, you may want to optimize the load on the machine by not creating useless sessions.

55.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=""/ >

56.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:

57.How do you connect to the database from JSP?
A Connection to a database can be established from a jsp page by writing the code to establish a connection using a jsp scriptlets.
Further then you can use the resultset object "res" to read data in the following way.
What is the page directive is used to prevent a JSP page from automatically creating a session?
<%@ page session="false">

58.How do you delete a Cookie within a JSP?
Cookie mycook = new Cookie("name","value");
response.addCookie(mycook);
Cookie killmycook = new Cookie("mycook","value");
killmycook.setMaxAge(0);
killmycook.setPath("/");
killmycook.addCookie(killmycook);

59.Can we implement an interface in a JSP?
No

60.What is the difference between ServletContext and PageContext?
ServletContext: Gives the information about the container
PageContext: Gives the information about the Request

61.How is JSP include directive different from JSP include action. ?
When a JSP include directive is used, the included file's code is added into the added JSP page at page translation time, this happens before the JSP page is translated into a servlet. While if any page is included using action tag, the page's output is returned back to the added page. This happens at runtime.

62.Can we override the jspInit(), _jspService() and jspDestroy() methods?
We can override jspinit() and jspDestroy() methods but not _jspService().

63.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.

64.How to pass information from JSP to included JSP?

Using <%jsp:param> tag.

65.Why is _jspService() method starting with an '_' while other life cycle methods do not?

_jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page.


66.What happens when a page is statically included in another JSP page?

An include directive tells the JSP engine to include the contents of another file (HTML, JSP, etc.) in the current page. This process of including a file is also called as static include.

67.A JSP page, include.jsp, has a instance variable "int a", now this page is statically included in another JSP page, index.jsp, which has a instance variable "int a" declared. What happens when the index.jsp page is requested by the client?

Compilation error, as two variables with same name can't be declared. This happens because, when a page is included statically, entire code of included page becomes part of the new page. at this time there are two declarations of variable 'a'. Hence compilation error.

68.Can you override jspInit() method? If yes, In which cases?

yes, we can. We do it usually when we need to initialize any members which are to be available for a servlet/JSP throughout its lifetime.

69.How does JSP handle runtime exceptions?
Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.

70.How can my application get to know when a HttpSession is removed?

Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.
Create an instance of that class and put that instance in HttpSession. 

71.What is the difference between directive include and jsp include?

<%@ include> : Used to include static resources during translation time. : Used to include dynamic content or static content during runtime.

72.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.

73.How to Retrieve Warnings?

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object

SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
while (warning != null)
{
System.out.println(\"Message: \" + warning.getMessage());
System.out.println(\"SQLState: \" + warning.getSQLState());
System.out.print(\"Vendor error code: \");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}

74.How many JSP scripting elements are there and what are they?

There are three scripting language elements: declarations, scriptlets, expressions.

75.What Class.forName will do while loading drivers?

It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

76.In the Servlet 2.4 specification SingleThreadModel has been deprecated, why?

Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

77.How can a servlet refresh automatically if some new data has entered the database?

You can use a client-side Refresh or Server Push.

78.The code in a finally clause will never fail to execute, right?

Using System.exit(1); in try block will not allow finally code to execute.

79.Is JSP technology extensible?

YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

80.Can we use the constructor, instead of init(), to initialize servlet?

Yes , of course you can use the constructor instead of init(). There’s nothing to stop you. But you shouldn’t. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won’t have access to a ServletConfig or ServletContext.

81.What is Servlet Invoker?

Servlet Invoker is used to dispatch servlets by class name. The purpose of Invoker Servlet allows a web application to dynamically register new servlet definitions that correspond with a servlet tag in the /WEB-INF/web.xml deployment descriptor.

82.How many messaging models do JMS provide for and what are they?

JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

83. What is Servlet LifeCycle?

Servlet Lifecycle has following three phases:
a)Creation and intialization : Handled by init() method.
b)Execution of service : Handled by service() method.
c)Destroy the servlet : Handled by destroy() method.

84.What is a Java servlet?

A Java servlet is a J2EE component that run on the Server. In other words A Java servlet runs in a Web server or application server and provides server-side processing like accessing a database and/or e-commerce transactions etc.

85.What is servlet mapping?

Servlet mapping maps url patterns to servlets.If a request from a client comes, servlet container decides to what application the request should be forwarded to.

86. How to get the current HttpSession object?

The current HttpSession object can be achieved by calling the getSession method on HttpServletRequest.

87. In the context of Servlet what is Filter?

Filters dynamically intercept request and response objects and change/use the data present in those objects while performing actions like authentication/style conversion etc.Filters are configured in the web deployment descriptor.

88. Why a constructor is not prefereble in java servlet?

Ideally we can define constructors in servlet. But the constructor cannot access the ServletConfig object.So To overcome this, init() method is used for initialization instead of declaring a constructor.

89.When we call the Destroy() method on the servelet will the servlet be destroyed?

No.When we call the Destroy() method on the servlet the the servlet will NOT be destroyed.Only the code inside the Destroy() method will be executed.The name of the Destroy() method is confusing ,actually it does not destroy the object but the code inside it runs when the object is destroyed.

90. What is meant by the Default initialization of Java Servelet?

In the Default initialization of Java Servlet,the java servlet is initialized when the servlet is called for the first time.Another term for this type of servlet initialization is called lazy loading.

91. How is HttpServlet is different from GenericServlet?

HttpServlet extends the GenericServlet ,thus inherits the properties of GenericServlet. Also HttpServlet defines a HTTP protocol specific servlet while GenericServlet defines a generic, protocol-independent servlet.

92.What is an Applet container?

An applet container is a resource which manages the execution of applets. It consists of a web browser as well as a Java plug-in which are running on the client together.

93.What is HTTP Servlet class?

The HTTP Servlet class is a service that provides an abstract class which has to be sub classified for a suitable website. These are the following methods-
doGet ()
doPost ()
doPutt ()
doDelete ()
inti ()
destroy ()
getServletInfo ()

94.What are advantages and selling points of a Servlet?

Servlet has many advantages and features, here are some-
A servlet can handle multiple requests at the same time and it can also synchronize requests.
This helps it to access other features like online real-time calling and conferencing.
Servlets are used to forward requests to other servers and servlets.
So, according to the type of requests, content and the type of organization; servlets can be used to provide a logical service over several servers.

95.What is a generic server class?

This class of Servlet implements both, servlet and servletconfig interfaces. It is extended by a server. With using generic sesrver class it gets easier to create Servlet based applications.

96.Which interface must be implemented by all servlets?

Servlet Interface.

97.Explain the lifecycle of a Servlet?

The lifecycle of every servlet is similar to each other. The server initializes the servlet (init ( )), and later the servlet handles zero or more client requests. Later, the server removes the servlet (destroy ()).

98.What is the difference between Applet and Servlet?

Applets are applications designed to be transferred over the network and executed by Java compatible browsers. It is a client side Java program that runs with a web browser of the client’s machine. It can be used with interface classes like AWT or Swing. The Applet cycle method is like this, init (), stop (), paint (), start (), destroy ().

Servlets are Java based analog to CGI programs. They are implemented by means of servlet containers which are associated with an HTTP server. It is a server side component which runs on the web server. The servlets does not have any user interface. Servlet cycle method is like, doGet (), doPost ().

99.How does an HTTP servlet handle client requests?

An HTTP servlet handles client requests via service method. It supports standard HTTP client requests; it then dispatches the requests to a method which is compatible with the request.

100.What is a container? What is a web container?

A container is the interface between a component and the low level platform, it supports the component. It must be assembled into J2EE application and deployed into its container. A web container is a combination of both, JSP and Servlet

101.What are the services of a container?

A container is a runtime support of a system-level entity. These containers provide components with lifecycle management, deployment and threading. A web container manages the execution of a JSp page while servlet components are used for J2EE apps.

102.Can you explain What is JSP page life cycle?

When first time a JSP page is request necessary servlet code is generated and loaded in the servlet container. Now until the JSP page is not changed the compiled servlet code serves any request which comes from the browser. When you again change the JSP page the JSP engine again compiles a servlet code for the same.
JSP page is first initialized by jspInit() method. This initializes the JSP in much the same way as servlets are initialized, when the first request is intercepted and just after translation.
Every time a request comes to the JSP, the container generated _jspService() method is invoked, the request is processed, and response generated.
When the JSP is destroyed by the server, the jspDestroy() method is called and this can be used for clean up purposes.
    
103.What is EL ?

EL stands for expression language. An expression language makes it possible to easily access application data.In the below expression amountofwine variable value will be rendered. There are ${amount} litres of milk in the bottle.
    
104.how does EL search for an attribute ?

EL parser searches the attribute in following order:
Page
Request
Session (if it exists)
Application
If no match is found for then it displays empty string.

105.How can we disable EL ?

We can disable using isELIgnored attribute of the page directive:
<%@ page isELIgnored ="true|false" %> .
    
106.what is JSTL ?
   
JSTL is also called as JSP tag libraries. They are collection of custom actions which can be accessed as JSP tags.
    
107.what the different types of JSTL tags are ?

Tags are classified in to four groups:-
Core tags
Formatting tags
XML tags
SQL tags

108.What is the use of ?

It includes the output of one JSP in to other JSP file at the location of the tag. Below is the syntax for the same:-
< jsp:include page="..some.url.." flush="true or false"/>-
page: A URL that is relative to the current JSP page at request time-
flush: Determines if the buffer for the output is flushed immediately, before the included page's output.
    
109.What is < jsp:forward> tag for ?
   
It forwards the current request to another JSP page. Below is the syntax for the same:-
< jsp:forward page="...url..." />
We can also forward parameter to the other page using the param tag
< jsp:forward page="..url...">
< jsp:param ..../>

110.How do we prevent browser from caching output of my JSP pages?
   
WE can prevent pages from caching JSP pages output using the below code snippet. <%response.setHeader("Cache-Control","no-cache"); //HTTP 1.1 response.setHeader("Pragma","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %>
    
111.How did you implement caching in JSP?
   
OSCache is an open-source caching library that's available free of charge from the OpenSymphony organization . OSCache has a set of JSP tags that make it easy to implement page caching in your JSP application.
Following are some Cache techniques it fulfills:-
Cache entry
An object that's stored into a page cache is known as a cache entry. In a JSP application, a cache entry is typically the output of a JSP page, a portion of a JSP page, or a servlet.

112.What are JSP directives ?

JSP directives do not produce any output. They are used to set global values like class declaration, content type etc. Directives have scope for entire JSP file. They start with <%@ and ends with %>. There are three main directives that can be used in JSP:-
page directive
include directive
taglib directive

Cache key:
A page cache is like a hash table. When you save a cache entry in a page cache, you must provide a cache key to identify the cache data. You can use keys like URI, other parameters like username, ipaddress to indentify cache data.
Cache duration
This is the period of time that a cache entry will remain in a page cache before it expires. When a cache entry expires, it's removed from the cache and will be regenerated again.

Cache scope:
This defines at what scope the data is stored application or session scope. <%= new java.util.Date().toString() %>
The above tag says that refresh after every 60 seconds the user requests data. So if user1 s requesting the page it will display fresh date and if an other user requests with in 60 seconds it will show same data. If any other user requests the page after 60 second he will again see refreshed date.
    
113.what are Page directives?
   
Page directive is used to define page attributes the JSP file. Below is a sample of the same:- <% @ page language="Java" import="java.rmi.*,java.util.*" session="true" buffer="12kb" autoFlush="true" errorPage="error.jsp" %>
To summarize some of the important page attributes:-
import :- Comma separated list of packages or classes, just like import statements in usual Java code.
session :- Specifies whether this page can use HTTP session. If set "true" session (which refers to the javax.servlet.http.HttpSession) is available and can be used to access the current/new session for the page. If "false", the page does not participate in a session and the implicit session object is unavailable.
buffer :- If a buffer size is specified (such as "50kb") then output is buffered with a buffer size not less than that value.
isThreadSafe :- Defines the level of thread safety implemented in the page. If set "true" the JSP engine may send multiple client requests to the page at the same time. If "false" then the JSP engine queues up client requests sent to the page for processing, and processes them one request at a time, in the order they were received. This is the same as implementing the javax.servlet.SingleThreadModel interface in a servlet.
rrorPage: - Defines a URL to another JSP page, which is invoked if an unchecked runtime exception is thrown. The page implementation catches the instance of the Throwable object and passes it to the error page processing.
    
114.How does JSP engines instantiate tag handler classes instances?
   
JSP engines will always instantiate a new tag handler instance every time a tag is encountered in a JSP page. A pool of tag instances are maintained and reusing them where possible. When a tag is encountered, the JSP engine will try to find a Tag instance that is not being used and use the same and then release it.
    
115.what’s the difference between JavaBeans and taglib directives?
   
JavaBeans and taglib fundamentals were introduced for reusability. But following are the major differences between them:-
Taglib are for generating presentation elements while JavaBeans are good for storing information and state.
Use custom tags to implement actions and JavaBeans to present information.
    
116.what are the different scopes an object can have in a JSP page?

There are four scope which an object can have in a JSP page:-
Page Scope
Objects with page scope are accessible only within the page. Data only is valid for the current response. Once the response is sent back to the browser then data is no more valid. Even if request is passed from one page to other the data is lost. Request Scope
Objects with request scope are accessible from pages processing the same request in which they were created. Once the container has processed the request data is invalid. Even if the request is forwarded to another page, the data is still available though not if a redirect is required. Session Scope
Objects with session scope are accessible in same session. Session is the time users spend using the application, which ends when they close their browser or when they go to another Web site. So, for example, when users log in, their username could be stored in the session and displayed on every page they access. This data lasts until they leave the Web site or log out. Application Scope
Application scope objects are basically global object and accessible to all JSP pages which lie in the same application. This creates a global object that's available to all pages. Application scope variables are typically created and populated when an application starts and then used as read-only for the rest of the application.
    
117.what are different implicit objects of JSP?
   
Below are different implicit objects of JSP
pageContext :- The PageContext object.
pageScope :- A Map of all the objects that have page scope.
requestScope :- A Map of all the objects that have request scope.
sessionScope :- A Map of all the objects that have session scope.
applicationScope :- A Map of all the objects that have application scope.
param :- A Map of all the form parameters that were passed to your JSP page (for example, the HTML < input name="someName" type="text"/> is passed to your JSP page as a form parameter).
paramValues :- HTML allows for multiple values for a single form parameter. This is a Map of all the parameters, just like param, but in this object the values are an array containing all of the values for a given parameter in the event that there's more than one. header :- A Map of all the request headers.
headerValues :- For the same reasons as paramValues, a headerValues object is provided.
cookie :- A Map of all the cookies passed to your JSP. The value returned is a Cookie object.
initParam :- A Map that maps context initialization parameter names to their parameter values.
    
118.What is JIT (Just-in-Time) Compilation ?
   
When JVM compiles the class file he does not compile the full class file in one shot. Compilation is done on function basis or file basis. Advantage gained from this is that heavy parsing of original source code is avoided. Depending on need basis the compilation is done. This typ of compilation is termed as JIT or Just-in- Time compilation.
    
119.How do you implement inheritance in Java?
   
inheritance is implemented by using “EXTEND” keyword.
    
120.How can we implement polymorphism in Java ?
   
Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon. There are two types of polymorphism:-
Method Polymorphism through overloading.
Object polymorphism by inheritance / interfaces.
    
121.What are packages ?
   
Packages group related classes and interfaces together and thus avoiding any name conflicts. From OOP’s point of view packages are useful for grouping related classes together. Classes are group together in a package using “package” keyword.
    
122.What is the use if “instanceof” keyword ?
   
“ instanceof ” keyword is used to check what is the type of object. F
    
123.What are Native methods in Java ?
   
There may be times when we want to call subroutines which are written in some other language other than Java like C++, VB6 etc.
    
124.Explain in depth Garbage collector ?
   
Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. This frees the programmer from having to keep track of when to free allocated memory, thereby preventing many potential bugs. Thus making programmers more productive as they can now put more effort in coding rather than worrying about memory management.
The only disadvantage of garbage collector is it adds overheads. Because the JVM (Java virtual machine) has to keep a constant track of the objects which are not referenced and then free these unreferenced objects on fly. This whole process has a slight impact on the application performance. But garbage collector has a good algorithm and it runs in its own thread thus having a least impact on the application performance but still it has some impact.
    
125.How can we force the garbage collector to run?
   
Garbage collector can be run forcibly using “System.gc()” or “Runtime.gc()”

------------------------------------
Also Read:
Advanced Java Interview Questions -1

Advanced Java Interview Questions -2

Advanced Java Interview Questions -3

Advanced Java Interview Questions -4

Advanced Java Interview Questions -5

Advanced Java Interview Questions -6

Advanced Java Interview Questions -7

Advanced Java Interview Questions -8

Advanced Java Interview Questions -9

Advanced Java Interview Questions -10

Advanced Java Interview Questions -11

Advanced Java Interview Questions -12

Advanced Java Interview Questions -13

Advanced Java Interview Questions -14        

0 comments:

Post a Comment