Saturday, October 31, 2009

Overview of Servlet Filters


Servlet Filters with example

One of the best features added to the Servlet 2.3 specificationwas support for Servlet Filters. A filter is an object that can transform arequest or modify a response. Note that filters are not Servlets and they arenot responsible for creating a response. They are preprocessors of requestsbefore they reach a Servlet and postprocessors of responses after leaving aServlet.

Servlet filters can:
Intercept a Servlet's invocation before the Servlet is called
Examine a request before the destination Servlet is invoked
Modify request headers and request data by subclassing theHttpServletRequest object and wrapping the original request
Modify the response headers and response data by subclassing theHttpServletResponse object and wrapping the original response
Intercept a Servlet's invocation after the servlet is called
Servlet filters are classes that implement the javax.servlet.Filter interface. This interface has three methods:
public interface Filter {
  public void init(FilterConfig filterConfig);
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain);
  public void destroy();
}
Where its methods have the following functionality:
·                init(): called when the filteris initialized and loaded into memory by the Servlet container; called when thefilter is being put into service
·                doFilter(): called by the Servletcontainer each time a request/response pair is passed through the chain due toa client request for a resource at the end of the chain. The FilterChain passedin to this method allows the Filter to pass on the request and response to thenext entity in the chain
·                destroy(): called just prior tothe filter being removed from memory; called when the filter is being taken outof service
When you filter’s doFilter method is invoked, you choose whether you want to performfunctionality before the rest of the chain is executed (or in our simpleexample: before the Servlet is invoked) and/or after the rest of the chain isexecuted. Calling the FilterChain’s doFilter()method causes the other filters or Servlets thatare handling a request to be invoked. You can call the doFilter() method at any time inyour doFilter() implementation.
As an example, let's look at a simple filter that records theresponse time of our HelloServlet(see the beginning ofJava Web Technologies.) We will not touch the HelloServlet code. Instead, we will create a filter class and then modifythe web deployment descriptor to tell the Servlet container to pass allrequests through our Servlet. Listing 1 shows the code for our TimerFilterclass.

Listing 1. TimerFilter

package com.techpage.webtechnologies;
 
import javax.servlet.*;
 
public class TimerFilter implements Filter
{
   private FilterConfig config;
 
   public void init(FilterConfig filterConfig) throws ServletException
   {
      this.config = filterConfig;
   }
 
   public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
              throws java.io.IOException, ServletException
   {
      // Record the start time of the request
      long before = System.currentTimeMillis();
 
      // Invoke the Servlet
      chain.doFilter( req, res );
 
      // Capture the end time of the request
      long after = System.currentTimeMillis();
 
      // Display the elapsed time to the standard output
      System.out.println("Elapsed Time: " + ( after - before ) + "ms" );   
   }
 
   public void destroy()
   {
      this.config = null;
   }
}
The focus of the TimerFilter class is the doFilter() method; the init and destroy methods manage an internal FilterConfig member variable that is not used in this example. ThedoFilter() method records the start time that the filter is invoked,executes the rest of the filter chain, and then captures the end time of therequest to display the elapsed time to the standard output.
The functionality of this filter is simple, but how do we hook itup to intercept Servlets? The answer is by modifying the web deploymentdescriptor. In the Servlet 2.3 specification, the following two sections wereadded to web deployment descriptor that parallel the Servlet descriptors:
·                filter: defines a unique filter name and the fully qualified classname that it references
·                filter-mapping: maps URLs to filters
So in this example we add the following to the beginning of theweb.xml file:
<filter>
  <filter-name>TimerFilter</filter-name>
  <filter-class>com.techpage.webtechnologies.TimerFilter</filter-class>
</filter>
 
 
<filter-mapping>
  <filter-name>TimerFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
This defines a TimerFilter as being implemented by thecom.techpage.webtechnologies.TimerFilter class and matching all URLs in our web application (bymatching the URL pattern “/*”.) So the complete web.xml file is shown inlisting 2.

Listing 2. Filterexample’s web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
                            "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">
 
<web-app>
  <filter>
    <filter-name>TimerFilter</filter-name>
    <filter-class>com.techpage.webtechnologies.TimerFilter</filter-class>
  <filter-mapping>
 
  <filter-mapping>
    <filter-name>TimerFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <servlet>
    <servlet-name>MyHelloServlet</servlet-name>
    <servlet-class>HelloServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>MyHelloServlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>
Build your WAR file as usual and drop the TimerFilter.class filein the /WEB-INF/classes/com/techpage/webtechnologies directory. Deploy your WARfile to your Servlet container, and then watch the output. The following issample output when deploying this WAR file to Jetty running inside JBoss:
00:49:57,382 INFO [STDOUT] Elapsed Time: 10ms
00:49:57,382 INFO [STDOUT] Elapsed Time: 0ms
00:49:57,382 INFO [STDOUT] Elapsed Time: 0ms
00:49:57,382 INFO [STDOUT] Elapsed Time: 10ms
00:49:57,382 INFO [STDOUT] Elapsed Time: 0ms
00:49:57,382 INFO [STDOUT] Elapsed Time: 10ms


Friday, October 30, 2009

Simple JSF Application



This is the simplest JSFapplication  that enables even a  novice to understand easily thesteps to follow to create own JSF application. In this example we will explainall you need, to develop this application like how to use JSF tags in JSPpages, how to configure the application through faces-config.xml, and web.xml,directory structure of the application etc. A detailed explanation of thisexample will definitely form a basis for you to develop  your own JSFapplication with more advanced functionality of JSF.

In this application thefirst page that comes in front of user contains an input text and a commandbutton components. User enters name in the input text and press the button. Assoon as the button is pressed next page is shown with the greeting content tothe user.


Steps Followed :
We will follow thefollowing steps to create this application :
  1. Create development directory structure (root directory and sub directories)
  2. Create and place configuration files in appropriate place
  3. Create JSP pages
  4. Create a properties file
  5. Create a managed bean
  6. Register managed bean in configuration file
  7. Define a navigation rule in configuration file
  8. Run the application
To understand clearlywhere to place which file, directory structure of this application will helpyou a lot. So have a look on it below:
Directory structure ofthis application :

Application Name: SimpleOne, the contents of this applicationare..
/index.jsp
/WEB-INF/web.xml

/WEB-INF/classes/techpage/PersonBean.class

/WEB-INF/classes/techpage/messages.properties
/WEB-INF/faces-config.xml
/pages/inputname.jsp
/pages/result.jsp
Create and placedirectories, configuration files :

In this application we used JDK 1.6.0 and TOMCAT 5.5.23 to deployand run this application. Install and configure TOMCAT for JSF.

Directories :
In tomcat, web applications are placed within webapps folder. Now we aregoing to start creating "SimpleOne" application so the firststep is to create a folder in web apps with the name "SimpleOne".This is the root directory of the application. Now create WEB-INFfolder in root directory and place web.xml and faces-config.xml file.

Configuration files :

  1. web.xml :

    You can get web.xml file from WEB-INF folder of any other application available in TOMCAT by default or you can create yourself with the same name and extention of the file i.e. "web.xml". If you are creating this file then take care of mentioning version of xml. For ex. <?xml version="1.0"?> at the top of file and after that  all elements will be written within web-app opening and closing tag i.e.<web-app> and </web-app> . So the root element of this file is <web-app>.
Sothe initial format of this file will be like this:
<?xml version="1.0"?> 
<web-app>
..................................
..................................
..................................
</web-app>
Soif you want to create this file then write above code in notepad and save itwith name "web.xml" in the WEB-INF folder of your application. After creating and placing this file to the appropriate position, we have toadd some elements within web-app tag. How and why we will write those elementswill be described later in this section.
  1. faces-config.xml
Nowwe come to the second file faces-config.xml that will be in the sameplace where web.xml is i.e. WEB-INF folder. Here also you have to takecare of mentioning version of xml as we did in web.xml file. All tag elementswill be within faces-config  opening and closing tag i.e. <faces-config>and </faces-config>. So the root element of this file is <faces-config>tag.
Soinitial format of this file will be like this:
<?xml version="1.0"?>
<faces-config>
.................................
.................................
.................................
</faces-config>
Youcan create this file also by your own or copy from other JSF Application . Ifyou want to create this file then you can write the above code in notepad andsave it with the name "faces-config.xml" in WEB-INF folder ofyour application. After creating and placing this file to the appropriateposition, we have to add some elements within faces-config tag. How we willwrite those elements will be described later in this section.
So now there will be two xml files web.xml and faces-config.xmlin WEB-INF directory.

This JSF applicationcontains:
  1. Three JSP pages for viewing purpose
  2. JavaBean to hold model data
  3. Configuration files specifying managed bean, navigation rules, controller servlet.
Now our first step is tocreate view for the application. For this we have created three JSP files givenbelow:
  1. index.jsp
  2. inputname.jsp
  3. result.jsp
Creating JSP pages:

index.jsp :
The index page is storedin root directory "SimpleOne". The code for "index.jsp"is :
<html>
   <body>
        <jsp:forward page="/pages/inputname.jsf" />
   </body>
</html>
Description :
As you can see in code above, this page simply forwards the user to the page "inputname.jsp"through <jsp:forward page="/pages/inputname.jsf" /> lineof code. Index page doesn't display anything to the user so you can leavecreating this page but it has one benefit that you can start application simplymentioning the application name and not specifying any file name at the end ofURL i.e. we can simply write
http://localhost:8080/SimpleOne  in the URL and see output of  the application.
So the first page that appears to the user is "inputname.jsp"not "index.jsp". The code for "inputname.jsp"is:

inputname.jsp :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="techpage.messages" var="message"/>

<f:view>
<html>
     <head><title>enter your name page</title></head>

     <body>
           <h:form>
                  <h1><h:outputText value="#{message.inputname_header}"/></h1>
                  <h:outputText value="#{message.prompt}"/>
                  <h:inputText value="#{StoreNameBean.personName}" />
                  <h:commandButton action="result" value="#{message.button_text}" />
           </h:form>
     </body>
</html>
</f:view>
Description :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
With taglib directive weinclude the JSF tag libraries. First line tells where to find JSF html tagsthat defines html elements and second line tells where to find JSF coretags. A page which contains JSF tags is represented by a tree ofcomponents. The root of this tree is UIViewRoot. This root isrepresented by view tag. So it is necessary to include all componenttags (tags representing UI components) within view tag.

<f:loadBundle basename="techpage.messages"var="message"/>

This line loads ourproperties file (resource bundle) that holds messages that we want to displayin our JSP page. Actually this file is a collection of param=value pair.The name of this file is "messages.properties" in thisapplication which is saved in  /WEB-INF/classes/techpage folder. Wewill explain more about this in subsequent section.

<h:form>

This tag creates htmlform using JSF tag. Typically JSP page includes a form, which is submittedwhen a button is clicked. Form components must be nested inside the form tag i.e. within <h:form> and </h:form>.
<h:outputTextvalue="#{message.inputname_header}"/>
This tag looks into theresource bundle i.e. properties file(messages.properties) . It looks the valuefor inputname_header parameter  in "message.properties"file and set the value of it to value attribute. Finally this tag prints thisvalue. So in this example this line prints "Techpage JSFTutorial".
<h:outputTextvalue="#{message.prompt}"/>
In this line the value of"prompt" param is looked  in "messages.properties"file and this tag prints this message. So in this example this line prints "EnterYour Name:".

<h:inputText value="#{StoreNameBean.personName}" />

This tag is used tocreate input text box component. The value attribute is used toconnect  this field to the managed bean attribute .Here StoreNameBeanis the name of Bean and personName is the name of attribute of bean.After pressing the submit  button bean gets the value in the input textbox filled by user . This bean is nothing but a Java Bean that containsattributes and setter and getter methods to set and get those attributes. Wewill explain more about Managed Bean later in this section.

<h:commandButton action="result"value="#{message.button_text}" />

This tag represents commandbutton component. Here again the value attribute gets its value from "messages.properties"file. So in this example this line prints "Submit" on buttoncomponent .The action attribute is used to see which page will be displayednext when we will press this button. This "result" value ismatched in faces-config.xml file in WEB-INF folder where navigationrules are defined. How to define navigation rules in faces-config.xml filewill be described later in this section. Here in this application the next pageis "result.jsp" when submit button is pressed..
The collective output oftags used in inputname.jsp page will give rise to the first pageappeared in front of the user:
 Here we have to enter the Name..
When above page appearsto the user, user enters name to the input text field and submits the button, anew page "result.jsp" is generated that welcomes the user withthe user name. The code for "result.jsp" is :

result.jsp :
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="techpage.messages" var="message"/>

<html>
     <head><title>greeting page</title></head>
    
     <body>
          <f:view>
          <h3><h:outputText value="Hi,#{StoreNameBean.personName}!" />
          <br/><h:outputText value="#{message.greeting_text}" /></h3>
          </f:view>
     </body>
</html>
Description :
First three lines aresame as in "inputname.jsp" file.
<h:outputText value="Hi, #{StoreNameBean.personName}!" />
This line is used to access the value of personName attribute from JavaBean named "StoreNameBean" and prints this value(i.e. person'sname) on the page.
<h:outputText value="#{message.greeting_text}" />
This line looks the value of greeting_text in "message.prorerties"file and prints this value to the page. Here this line prints "WelcomeIn Techpage JSF Tutorial".

Output of result.jsp :
So output will belike this (if "sky" is entered in the text field of"inputname.jsp" page):
Hi,sky! Along with thewelcome text..
Now we come to those topicsthat has been left unexplained above.

Creating properties file(resource bundle) :

In above JSP files we have used "message.properties" file.This is a properties file and is a collection of param=value pairs. Wecan use there values of param in our JSP file as we did it previously. Thisprovides a great benefit to the application like we can modify these valueseasily and there is no need to change the JSP file. In this application we havecreated "messages.properties" file in techpage folder in WEB-INF/classesfolder. The code for this file is:

inputname_header=Techpage JSF Tutorial
prompt=Enter Your Name:
greeting_text=Welcome In Techpage JSF Tutorial
button_text=Submit
Creating Managed Bean :
In the above JSP files wehave used Managed Bean named "StoreNameBean". For this we havecreated "PersonBean.java" file. This Managed Bean is nothingbut a Java Bean that contains attributes and setter and getter methods to setand get those attributes. Here in this example there is only one attributenamed "personName" and so only one setter method setPersonName()and one getter method getPersonName() for that attribute. This bean isused to get  values entered by user after submit button is pressed. Makesure the attribute in this class must be same as the field name in JSP. In thisexample this file is created in package techpage. So compile this fileand place its class file i.e. PersonBean.class in techpage folderin WEB-INF\classes folder. The code for this class is:
package techpage;

public class PersonBean {
   String personName;  
   public String getPersonName() {
      return personName;
   }

   public void setPersonName(String name) {
      personName = name;
   }
}

If you want to access the bean classes in your JSP files, you have to registerthe bean classes in faces-config.xml. So now its turn to declare this bean inconfiguration file faces-config.xml that has been described in the next sectionbelow:

Registering managed bean :

We have already created faces-config.xml file with empty <faces-config>tag. This configuration file is used to register managed beans, specifyingnavigation rules etc. We will add <managed-bean> element within <faces-config>and </managed-bean> tag to register Managed Bean. So thisregistration code will be like this for this application:
 

<managed-bean>
<managed-bean-name>StoreNameBean</managed-bean-name>
<managed-bean-class>techpage.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<managed-bean> defines a managed bean. Bean'name is given in <managed-bean-name>tag.This name is used in JSP files to represent the bean. The class name whichcorresponds to this bean is given in <managed-bean-class> tag. Todefine the scope for the bean we specify this in <managed-bean-scope>tag. In this Application name of the bean that will be used in JSP files is StoreNameBeanthat is represented by the bean class PersonBean in techpage package.
Defining navigation rule :
Now we will understandhow navigation from one page to the next page is performed as in ourapplication inputname.jsp page navigates to result.jsp page when user pressessubmit button after filling text in input text field. To understand this wecome back to the the line of code used in "inputname.jsp":
<h:commandButton action="result"value="#{message.button_text}" />
Here action attribute is set to "result". When user presses thecommand button then which page will be displayed is determined by thenavigation rule defined in faces-config.xml configuration file. Thisrule has been defined like this for our application :

<navigation-rule>
<from-view-id>/pages/inputname.jsp</from-view-id>
<navigation-case>
<from-outcome>result</from-outcome>
<to-view-id>result.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule> defines  navigation rule. <from-view-id>is used to specify the jsp file for which  navigation rule is to bedefined. So here we write the name of the JSP file for which the we aredefining the navigation rule. Here in our application it is inputname.jspthat is in pages package.<navigation-case>  specifiesthe value which is matched with the value specified in action attribute ofcommandButton tag. If it matches then the page specified within <to-view-id>tag is displayed. Here in our application it is "result.jsp".
So after editingfaces-config.xml file, it will look like following:
<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>
     <managed-bean>
          <managed-bean-name>StoreNameBean</managed-bean-name>
          <managed-bean-class>techpage.PersonBean</managed-bean-class>
          <managed-bean-scope>request</managed-bean-scope>
     </managed-bean>
     <navigation-rule>
          <from-view-id>/pages/inputname.jsp</from-view-id>
          <navigation-case>
               <from-outcome>result</from-outcome>
               <to-view-id>result.jsp</to-view-id>
          </navigation-case>
     </navigation-rule>
</faces-config>
Editing web.xml :
The FacesServlet servletworks as an engine for all JSF applications. So as we are using JSF frameworkin our web application, we will edit the deployment descriptor file web.xml todefine "FaceServlet" and its mapping in web.xml file. 
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>

<!-- Faces Servlet Mapping -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet> element is used to map the "javax.faces.webapp.FacesServlet"servlet class to a symbolic name i.e. Faces Servlet is an alias for"javax.faces.webapp.FacesServlet" servlet .So <servlet> tagregisters the Faces servlet.<servlet-mapping> element is used tomap any request of pattern like .jsf in the URL must be passed to theFaces servlet.

The FacesServlet servlet works as an engine for all JSF applications( handlingof all JSF related requests, building component tree of the JSP page, accessingall JSP pages in the application, creating an Event object and passing it toany registered listener). So all requests that need FacesServlet processingmust be directed to this servlet. So if we want to invoke this servlet withevery request we have to do mapping in <servlet-mapping> element. This isdone to map a particular URL pattern with the Faces servlet. URL of everyrequest must contain <file name>.jsf pattern because we havementioned this pattern in <url-pattern> tag.

If we look in "index.jsp" file, we will find that there is .jsf file suffix not .jsp in the path for the forward.
<jsp:forward page="/pages/inputname.jsf" />
This is done to map a particular URL pattern with the Faces servlet. This isused here because we have used *.jsf in the URL pattern in the web.xmlfile for the application. This is used to signal that the forwarded page shouldbe handled by the FacesServlet servlet within Tomcat.

Running the application :
This application is now complete. To run this application start Tomcat serverand type 
http://localhost:8080/SimpleOne URL in the address bar of your browser and hit enter.



Thursday, October 29, 2009

What is the difference Between if(null == myVariable) and if(myVariable == null)


null check

Putting equality comparisons back-to-front issomething that is usually done to avoid accidentally doing anassignment, by mis-typing "=" where you meant "==". By putting theconstant (e.g. null) first, you make this mis-typing cause acompilation error, which is good, because it alerts you earlier to yourmistake. It is more important in C and C++ than Java, because themis-typed expression is more likely to be legal in C/C++ than in Java.

Having decided to do equality tests back-to-front, some people decideto do all tests back-to-front, for consistency. Dunno if I agree withthat.


Wednesday, October 28, 2009

What is Generics in Java and how to use them


When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.
Here is a simple example taken from the existing Collections tutorial:


// Removes 4-letterwords from c. Elements must be strings
static voidexpurgate(Collection c) {
for (Iterator i = c.iterator();i.hasNext(); )
if (((String) i.next()).length() == 4)
i.remove();
}
Here is the same examplemodified to use generics:
static voidexpurgate(Collection<String> c) {
for(Iterator<String> i = c.iterator();i.hasNext(); )
if (i.next().length() == 4)
i.remove();
}
When you see the code <Type>,read it as “of Type”; the declaration above reads as “Collection of Stringc.” The code using generics is clearer and safer. We have eliminated an unsafecast and a number of extra parentheses. More importantly, we have moved part ofthe specification of the method from a comment to its signature, so thecompiler can verify at compile time that the type constraints are not violatedat run time. Because the program compiles without warnings, we can state withcertainty that it will not throw a ClassCastException at run time.The net effect of using generics, especially in large programs, is improved readability and robustness.
Generics has been added to the Java programming language in 2004 as part ofJ2SE 5.0.

As per JavaTM Language Specification
§ A type variable is an unqualified identifier. Typevariables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.
§ A class is generic if it declares one or moretype variables. These type variables are known as the type parameters of theclass. It defines one or more type variables that act as parameters. A genericclass declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized typesshare the same class at runtime.
§ An interface is generic if it declares one or moretype variables. These type variables are known as the type parameters of theinterface. It defines one or more type variables that act as parameters. Ageneric interface declaration defines a set of types, one for each possibleinvocation of the type parameter section. All parameterized types share thesame interface at runtime.
§ A method is generic if it declares one or moretype variables. These type variables are known as the formal type parameters ofthe method. The form of the formal type parameter list is identical to a typeparameter list of a class or interface.
§ A constructor can be declared as generic,independently of whether the class the constructor is declared in is itselfgeneric. A constructor is generic if it declares one or more type variables.These type variables are known as the formal type parameters of theconstructor. The form of the formal type parameter list is identical to a typeparameter list of a generic class or interface.

Simple Example
The following block of Java code illustrates a problem that existswhen not using generics. First, it declares an ArrayList oftype Object. Then, itadds a String to the ArrayList. Finally, it attempts to retrievethe added String and cast it to an Integer.
  List v = new ArrayList();
  v.add("test");
  Integer i = (Integer)v.get(0);
Although the code compiles without error, it throws a runtimeexception (java.lang.ClassCastException)when executing the third line of code. This type of problem can be avoided byusing generics and is the primary motivation for using generics.
Using generics, the above code fragment can be rewritten asfollows:
  List<String> v = new ArrayList<String>();
  v.add("test");
  Integer i = v.get(0); // (type error)
The type parameter String within the angle brackets declares the ArrayList tobe constituted of Strings (adescendant of the ArrayList's generic Object constituents).With generics, it is no longer necessary to cast the third line to anyparticular type, because the result of v.get(0) is defined as String bythe code generated by the compiler.
Compiling the third line of this fragment with J2SE 5.0 (or later)will yield a compile-time error because the compiler will detect that v.get(0) returns String insteadof Integer.
Wildcards
Generic type parameters in Java are not limited to specificclasses. Java allows the use of wildcards to specify bounds on the type ofparameters a given generic object may have. Wildcards are type parameters ofthe form "?", possibly annotated with a bound. Given that the exactelement type of an object with a wildcard is unknown, restrictions are placed onthe type of methods that may be called on the object.
As an example of an unbounded wildcard, List<?> indicates a list which has an unknownobject type.Methods whichtake such a list as an argument can take any type of list, regardless ofparameter type. Readingfrom the list will return objects of type Object, and writingnon-null elementsto the list is not allowed, since the parameter type is not known.
To specify the upper bound of a generic element, the extends keywordis used, which indicates that the generic type is a subtype of the bounding class.Thus it must either extend the class, or implement the interface of thebounding class. So List<? extends Number> means that the given list containsobjects of some unknown type which extends the Number class.For example, the list could be List<Float> orList<Number>. Reading an element fromthe list will return a Number, whilewriting non-null elements is once again not allowed.
The use of wildcards above are necessary since objects of one typeparameter cannot be converted to objects of another parameter. Neither List<Number> nor List<Float> is a subtype of the other (even thoughFloat is a subtype of Number). So, code that deals with List<Number> does not work with List<Float>. (If it did, it would bepossible to insert a Number that is not a Float intoit, which violates type safety.) The solution with wildcards works because itdisallows operations that would violate type safety.
To specify the lower bounding class of a generic element, the super keywordis used. This keyword indicates that the aforementioned generic type is asuper-type of said bounding class. So, List<? super Number> could represent List<Number> or List<Object>. Reading from a listdefined as List<? super Number> returns elements of type Object. Writing to such a list requires elementsof type Number or its subclasses.
Generic class definitions
Here is an example of a generic class:
public class Pair<T, S>
{
  public Pair(T f, S s)
  { 
    first = f;
    second = s;   
  }
 
  public T getFirst()
  {
    return first;
  }
 
  public S getSecond() 
  {
    return second;
  }
 
  public String toString()
  { 
    return "(" + first.toString() + ", " + second.toString() + ")"; 
  }
 
  private T first;
  private S second;
}
This generic class can be used in the following way:
Pair<String, String> grade440 = new Pair<String, String>("mike", "A");
Pair<String, Integer> marks440 = new Pair<String, Integer>("mike", 100);
System.out.println("grade:" + grade440.toString());
System.out.println("marks:" + marks440.toString());
Generic method definitions
Here is an example of a generic method using the generic classabove:
public <T> Pair<T,T> twice(T value)
{
   return new Pair<T,T>(value,value);
}
In many cases the user of the method need not indicate the typeparameters, as they can be inferred:
Pair<String, String> pair = twice("Hello");
The parameters can be explicitly added if needed:
Pair<String, String> pair = this.<String>twice("Hello");

Generics in throws clause
Although exceptions themselves cannot be generic, genericparameters can appear in a throws clause:
public <T extends Throwable> void throwMeConditional
      (boolean conditional, T exception) throws T
{
   if(conditional)
     throw exception;
}
Type erasure
Generics are checked at compile-time for type correctness. Thegeneric type information is then removed via a process called type erasure. For example, List<Integer> will be converted to the raw type (non-generic type) List, which can contain arbitrary objects.However, due to the compile-time check, the resulting code is guaranteed to betype correct, as long as the code generated no unchecked compiler warnings.
As a result, there is no way to tell at runtime which typeparameter is used on an object. For example, when an ArrayList isexamined at runtime, there is no general way to tell whether it was anArrayList<Integer> or an ArrayList<Float>. (There are partialapproaches — for example, individual elements may be examined to see what typethey belong to, since an ArrayList<Float> should never contain an Integer andvice versa; and it can be determined using reflection ifthe ArrayList actually belongs to anon-parameterized subtype of a specific ArrayList type, such as an ArrayListOfFloatsthat's declared to extend ArrayList<Float> — but no approach will work in allcases.)
The following code demonstrates that the Class objects appear thesame:
ArrayList<Integer> li = new ArrayList<Integer>();
ArrayList<Float> lf = new ArrayList<Float>();
if (li.getClass() == lf.getClass()) // evaluates to true
  System.out.println("Equal");
Java generics differ from C++ templates. Java generics generate onlyone compiled version of a generic class or function regardless of the number oftypes used. Furthermore, the Java run-time environment does not need to knowwhich parameterized type is used because the type information is validated atcompile-time and erased from the compiled code. Consequently, one cannotinstantiate a Java class of a parameterized type because instantiation requiresa call to a constructor, which is not possible when the type is unknown at bothcompile-time and runtime.
T instantiateElementType(List<T> arg)
{
  return new T(); //causes a compile error
}
Because there is only one copy of a generic class, staticvariables are shared among all the instances of the class, regardless of theirtype parameter. As a result, the type parameter cannot be used in thedeclaration of static variables or in static methods. Static variables andstatic methods are "outside" of the scope of the class'sparameterized types.