Tuesday 29 October 2013

Difference between == and .equals in java

package com.karthik;

/**
* @author karthik
*
*/
public class SimpleDifference {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String name = "karthik";
String name1 = "karthik";
String a = new String("karthi");
String b = new String("karthi");
/*
* In Java, when the “==” operator is used to compare 2 objects, it
* checks to see if the objects refer to the same place in memory. In
* other words, it checks to see if the 2 object names are basically
* references to the same memory location. A very simple example will
* help clarify this:
*/
if (name == name1) {
System.out.println("success");// compare the memory location
} else {
System.out.println("failure");
}

if (a == b) {
System.out.println("success1");
} else {
System.out.println("failure1");//compare the memory location
}

/*
* Now that we’ve gone over the “==” operator, let’s discuss the
* equals() method and how that compares to the “==” operator. The
* equals method is defined in the Object class, from which every class
* is either a direct or indirect descendant. By default, the equals()
* method actually behaves the same as the “==” operator – meaning it
* checks to see if both objects reference the same place in memory.
* But, the equals method is actually meant to compare the contents of 2
* objects, and not their location in memory.
*/
if (name.equals(name1)) {
System.out.println("success2");//compare the contents of 2 objects
} else {
System.out.println("failure2");
}

if (a.equals(b)) {
System.out.println("success3");//compare the contents of 2 objects
} else {
System.out.println("failure3");
}

}



}

difference between string and stringbuffer

String                                          StringBuffer

Immutable                                       Mutable
String s=new String("karthik");                StringBuffer sb=new StringBuffer("karthik")
s.concat("reddy");                             sb.append("reddy");
System.out.println(s);                         System.out.println(sb);
O/P:karthik                                    O/P:karthikreddy

--->once we created a String object            ---->once we created a StringBuffer object
we can't perform any changes in the existing  we can perform any changes in the existing
object.If we are trying to perform any        object.It is nothing but mutablity of 
changes with those changes a new object       of a StrongBuffer object
will be created.It is nothing but Immutability
of a String object

Use String--->If you require immutabilty
Use StringBuffer---->If you require mutable + threadsafety
Use StringBuilder--->If you require mutable + with out threadsafety

String s=new String("karthik");
--->here 2 objects will be created one is heap and the other is in stringconstantpool(scp) and s is always pointing to heap object

String s="karthik"; 
--->In this case only one object will be created in scp and s is always pointing to that object only


Sunday 27 October 2013

jsp interview questions and answers


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.

How can one Jsp Communicate with Java file.

Ans:we have import tag <%@ page import="cricket.info.*” %> like this we can import all the java file to our jsp and use them as a regular class another way is servlet can send the instance of the java class to our jsp and we can retrieve that object from the request obj and use it in our page.

Difference Between include Directive and include Action of JSP

Include Directive
Include Action
include directive is processed at the translation time
Include action is processed at the run time.
include directive can use relative or absolute path
Include action always use relative path
Include directive can only include contents of resource it will not process the dynamic resource
Include action process the dynamic resource and result will be added to calling JSP
We can not pass any other parameter
Here we can pass other parameter also using JSP:param
We cannot pass any request or response object to calling jsp to included file or JSP or vice versa
In this case it’s possible.


what are the implicit Object

Ans: This is a fact based interview question what it checks is how much coding you do in JSP if you are doing it frequently you definitely know them. Implicit object are the object that are created by web container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.they are bydefault available in JSP page.
They are: request, response, pageContext, session, and application, out, config, page, and exception.

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.

how does EL search for an attribute ?

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

What are the implicit EL objects in JSP ?

Following are the implicit EL objects:-
PageContext: The context for the JSP page.
Provides access to various objects for instance:-
servletContext: The context for the JSP page's servlet and any web components contained n the same application.
session: The session object for the client.
request: The request triggering the execution of the JSP page.
response: The response returned by the JSP page. See Constructing Responses.
In addition, several implicit objects are available that allow easy access to the following objects:
param: Maps a request parameter name to a single value
paramValues: Maps a request parameter name to an array of values
header: Maps a request header name to a single value
headerValues: Maps a request header name to an array of values
cookie: Maps a cookie name to a single cookie

initParam: Maps a context initialization parameter name to a single value
Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope: Maps page-scoped variable names to their values
requestScope: Maps request-scoped variable names to their values
sessionScope: Maps session-scoped variable names to their values
applicationScope: Maps application-scoped variable names to their values

How can we disable EL ?

We can disable using isELIgnored attribute of the page directive:
<%@ page isELIgnored ="true|false" %> .

what is JSTL ?

JSTL is also called as JSP tag libraries. They are collection of custom actions which can be accessed as JSP tags.
what the different types of JSTL tags are ?

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



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




How does JSP differ from a desk top application?

A. Desktop applications (e.g. Swing) are presentation-centric, which means when you click a menu item you know which window would be displayed and how it would look. Web applications are resource-centric as opposed to being presentation-centric. Web applications should be thought of as follows: A browser should request from a server a resource (not a page) and depending on the availability of that resource and the model state, server would generate different presentation like a regular “read-only” web page or a form with input controls, or a “page-not-found” message for the requested resource. So think in terms of resources, not pages. 

Servlets and JSPs are server-side presentation-tier components managed by the web container within an application server. Web applications make use of HTTP protocol, which is a stateless request-response based paradigm. JSP technology extends the Servlet technology, which means anything you can do with a Servlet you can do with a JSP as well.


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 %>

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

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

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

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.

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.

What are the two kinds of comments in JSP and what's the difference between them ?

<%-- JSP Comment --%>
<!-- HTML Comment -->

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.




Friday 25 October 2013

view resolvers in spring mvc

Spring provides view resolvers, which enable you to render models in a browser without tying you to a specific view technology. Out of the box, Spring enables you to use JSPs, Velocity templates and XSLT views

The two interfaces which are important to the way Spring handles views are ViewResolver and View.

The ViewResolver provides a mapping between view names and actual views.

The View interface addresses the preparation of the request and hands the request over to one of the view technologies.

AbstractCachingViewResolver--
An abstract view resolver which takes care of caching views. Often views need preparation before they can be used, extending this view resolver provides caching of views.

XmlViewResolver--
An implementation of ViewResolver that accepts a configuration file written in XML with the same DTD as Spring's XML bean factories.The default configuration file is /WEB-INF/views.xml.

ResourceBundleViewResolver--
An implementation of ViewResolver that uses bean definitions in a ResourceBundle, specified by the bundle basename. The bundle is typically defined in a properties file, located in the classpath. The default file name is views.properties.

UrlBasedViewResolver--
A simple implementation of the ViewResolver interface that effects the direct resolution of symbolic view names to URLs, without an explicit mapping definition. This is appropriate if your symbolic names match the names of your view resources in a straightforward manner, without the need for arbitrary mappings.

InternalResourceViewResolver--
A convenience subclass of UrlBasedViewResolver that supports InternalResourceView(i.e. Servlets and JSPs), and subclasses such as JstlView and TilesView. The view class for all views generated by this resolver can be specified via setViewClass(..). See the Javadocs for the UrlBasedViewResolver class for details.

VelocityViewResolver/FreeMarkerViewResolver--
A convenience subclass of UrlBasedViewResolver that supports VelocityView (i.e. Velocity templates) orFreeMarkerView respectively and custom subclasses of them.
Ex:

when using JSP for a view technology you can use the UrlBasedViewResolver. This view resolver translates a view name to a URL and hands the request over to the RequestDispatcher to render the view

    <bean id="viewResolver"  
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>
When mixing different view technologies in a web application, you can use the ResourceBundleViewResolver


    <bean id="viewResolver"  
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
    <property name="basename" value="views"/>
    <property name="defaultParentView value="parentView"/>
</bean>