    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: J2SE 5.0 New Features</title>
        <link>https://members.accu.org/index.php/articles/832</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 17, #5 - Oct 2005</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c94/">175</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-94/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+94/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;J2SE 5.0 New Features</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 02 October 2005 06:00:00 +01:00 or Sun, 02 October 2005 06:00:00 +01:00</p>
<p><strong>Summary:</strong>&nbsp;<p>J2SE 5.0 has been available for download since the end of 2004. This new release included many changes and enhancements to the Java platform such as speed and stability. Additionally, some changes were made to the Java language itself.</p></p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>J2SE 5.0 has been available for download since the end of 2004.
This new release included many changes and enhancements to the Java
platform such as speed and stability. Additionally, some changes
were made to the Java language itself. These fairly major changes
made to the language are:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Generics</p>
</li>
<li>
<p>Enhanced for loop</p>
</li>
<li>
<p>Annotations (sometimes called metadata).</p>
</li>
<li>
<p>Autoboxing and unboxing</p>
</li>
<li>
<p>Typesafe enumerations</p>
</li>
<li>
<p>Variable arguments (varargs)</p>
</li>
<li>
<p>Static imports</p>
</li>
</ul>
</div>
<p>Using these new language features in your applications can have
a big effect on your code, so this article aims to provide an
overview of these new features so that you can start leveraging
them in your code. As a Java developer I make extensive use of
these features now and find that they bring the Java language much
more upto date.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e48" id="d0e48"></a>Getting the
JDK</h2>
</div>
<p>The latest version of J2SE can be downloaded from Sun's website
if you are a Windows/Linux developer or from Apple's website if you
are an Apple developer. I'm not going to provide details about how
to install the JDK as this is primarily an article about the new
J2SE 5.0 features. Before you start developing however, its worth
checking that you have the correct version of Java installed.
Running java -version should produce output similar to the
following.</p>
<pre class="screen">
C:\&gt;java -version
java version &quot;1.5.0_03&quot;
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_03-b07)
Java HotSpot(TM) Client VM (build 1.5.0_03-b07, mixed mode, sharing)
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e55" id="d0e55"></a>Generics</h2>
</div>
<p>What are generics? Generics are akin to templates in C++ in that
they allow developers to write type safe code that operates on
different types of objects. This is very useful when dealing with
collections as it is no longer necessary to cast objects to
specific types when extracting them from collections. This
therefore eliminates the potential for getting ClassCastExceptions
and makes code much easier to read.</p>
<p>In this trivial example, consider a collection of Strings (it
doesn't have to be strings however, you could have a collection of
any type of object). Prior to Java 5, if you wanted to extract the
contents of a collection, you would use code such as that
below:</p>
<pre class="programlisting">
import java.util.*;

public class Generic {

  public static void main(String[] args) {
  // Create a collection and add some items to  
  // it.
    Collection languages = new ArrayList();
    languages.add(&quot;Java&quot;);
    languages.add(&quot;C#&quot;);
    // Now get the items from the collection.
    Iterator iterator = languages.iterator();
    while (iterator.hasNext()) {
      System.out.println(
         (String)iterator.next());
    }
  }
}
</pre>
<p>Notice that to extract objects from the collection, we have to
explicitly cast the retrieved objects to be Strings (or whatever
class the collection consists of), potentially allowing us to get
the dreaded <tt class="exceptionname">ClassCastException</tt> if we
had inadvertently added the wrong type of object to the collection
in the first place. Also, its difficult to see from looking at the
code what the collection contains. If there was an API method like
the following, what exactly would the collection contain?</p>
<pre class="programlisting">
public doStuff(Collection items)
</pre>
<p>Using generics, our simple application can be re-written to get
rid of the cast and made type safe.</p>
<pre class="programlisting">
import java.util.*;

public class Generic2 {
  public static void main(String[] args) {
  // Create a collection and add some items to 
  // it.
    Collection&lt;String&gt; languages = 
       new ArrayList&lt;String&gt;();
    languages.add(&quot;Java&quot;);
    languages.add(&quot;C#&quot;);
    // Now get the items from the collection.
    Iterator iterator = languages.iterator();
    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
}
</pre>
<p>You can see that the collection has been explicitly declared to
contain only <tt class="classname">String</tt> objects. Also note,
that there is no cast required to extract items from the
collection. The VM knows exactly what type of object is in the
collection and knows how to return it to the calling application.
If we tried to put something into the collection that isn't of the
required type (in our small example, anything other than a String),
then the code will simply fail to compile.</p>
<p>If we now re-wrote our rather obscure method doStuff, it may
look something like the following. Here we can see exactly what
type of object the collection contains.</p>
<pre class="programlisting">
public doStuff (Collection&lt;String&gt; items)
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e84" id="d0e84"></a>Enhanced for
Loop</h2>
</div>
<p>The enhanced for loop construct available in Java 5 allows us to
refine this code even further and remove the need for using the
Iterator to loop through the collection. This construct allows our
simple application to be re-written, yet again, as:</p>
<pre class="programlisting">
import java.util.*;

public class Generic3 {
  public static void main(String[] args) {
    // Create a collection and add some items
    // to it.
    Collection&lt;String&gt; languages = 
       new ArrayList&lt;String&gt;();
    languages.add(&quot;Java&quot;);
    languages.add(&quot;C#&quot;);
    // Now get the items from the collection.
    for (String language : languages) {
      System.out.println(language);
    }
  }
}
</pre>
<p>This new construct is declaring that the code should loop
through each entry in the collection languages. Each entry in the
collection will be declared as a <tt class="classname">String</tt>
called language which is then printed out to the console.</p>
<p>Hopefully you'll agree that these new features of Generics and
the enhanced <tt class="literal">for</tt>-loop allow Java
developers to write cleaner and safer code.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e101" id=
"d0e101"></a>Annotations</h2>
</div>
<p>Annotations provide a new feature to the Java language that
potentially allow a vast amount of time to be saved when developing
applications. They've been available in C# from the beginning and
are now available to Java developers.</p>
<p>Annotations allow developers to add &quot;hints&quot; into their code (in
a similar fashion to <span class="application">Xdoclet</span> or
<span class="application">JavaDoc</span> tags) that the compiler
can interpret at compile time. This allows the build process to do
a variety of things such as produce artifacts that would otherwise
have to be manually created, or to check that code complies with
certain criteria.</p>
<p>There are 3 annotations that are supplied with J2SE 5.0, but
developers have the ability to write additional annotations if they
desire. These 3 basic annotations are <tt class=
"literal">@Override</tt>, <tt class="literal">@Deprecated</tt> and
<tt class="literal">@Suppress</tt>.</p>
<p><tt class="literal">@Override</tt> is applied to methods and is
used by the compiler to check that overridden methods are declared
correctly. A simple example of this would be to apply it to the
<tt class="methodname">toString()</tt> method of a class.
<tt class="literal">@Override</tt> checks that the method to which
it is applied correctly overrides its parent object. If the method
is overridden incorrectly (e.g. it is spelt incorrectly or has the
wrong signature) then a compile time error will be generated.</p>
<pre class="programlisting">
public class Annotation1 {

  @Override
  public String toStrng() {
    return &quot;...&quot;;
  }

}
</pre>
<p>In this code fragment above, the method <tt class=
"methodname">toString()</tt> has been declared incorrectly, e.g.
<tt class="literal">public String toStrng()</tt> - note the
deliberate spelling mistake. The <tt class="literal">@Override</tt>
tag causes an error to be issued at compilation time.</p>
<pre class="screen">
C:\&gt;javac Annotation1.java
Annotation1.java:3: method does not override a method from its superclass
        @Override
         ^
1 error
</pre>
<p><tt class="literal">@Deprecated</tt> is applied to methods in a
similar fashion to <tt class="literal">@Override</tt>. This
annotation will cause a compiler warning to be issued if a
deprecated method is used. Finally, <tt class=
"literal">@Supress</tt> is used to tell the compiler to suppress
specified warnings.</p>
<p>The use of annotations is particularly of importance in the J2EE
arena and is becoming more important in the strive to make J2EE
easier. A couple of examples of this are Webservices (JAX-WS 2.0)
and Enterprise Java Beans (EJB 3). The J2EE 1.4 way of creating web
service and EJBs involves creating several different interfaces and
various verbose XML configuration files that describe the
webservices and EJBs being developed. With JAX-WS annotations, it
will be possible to declare that a class should be exposed as a web
service simply by putting a @WebService annotation before the class
declaration. With EJBs its very similar. To declare a class as a
stateless session bean is simply a matter of putting the @Stateless
annotation before the class declaration. Of course there are more
options that can be added into web services and EJBs to control
their behaviour, but the fundamental principal is that all these
options can be specified <span class="emphasis"><em>in
code</em></span> as annotations.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e165" id="d0e165"></a>Autoboxing /
Unboxing</h2>
</div>
<p>Autoboxing and unboxing allows Java code to automatically
convert between the basic primitive types (<tt class=
"type">int</tt>, <tt class="type">long</tt>, <tt class=
"type">double</tt> etc) and their class equivalents (<tt class=
"classname">Integer</tt>, <tt class="classname">Long</tt>,
<tt class="classname">Double</tt> etc.) and vice-versa. Prior to
Java 5, if you needed to convert an <tt class=
"classname">Integer</tt> to an <tt class="type">int</tt>, the code
required would look something like</p>
<pre class="programlisting">
public class Autoboxing {
  public static void main(String[] args) {
    int value = 10;
    Integer newValue = new Integer(value);
    Autoboxing ab = new Autoboxing();
    ab.doStuff(newValue);
  }
  public void doStuff(Integer value) {
    System.out.println(value);
  }
}
</pre>
<p>In this code, the wrapper class <tt class=
"varname">newValue</tt> has to be directly instantiated from the
varible <tt class="varname">value</tt> to be passed into the
method. With Autoboxing, this is no longer required as the int will
be converted into an Integer for us:</p>
<pre class="programlisting">
public class Autoboxing2 {
  public static void main(String[] args) {
    int value = 10;
    Autoboxing2 ab = new Autoboxing2();
    ab.doStuff(value);
  }
  public void doStuff(Integer value) {
    System.out.println(value);
  }
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e206" id="d0e206"></a>Static
Import</h2>
</div>
<p>Static imports are probably one of the least used features
available to Java 5. They allows you to specify static variables in
another class without having to specify the fully qualified name of
the class being imported. Members can be statically imported into a
class using the import static construct.</p>
<pre class="programlisting">
import static my.class.static.member;
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e213" id="d0e213"></a>Summary</h2>
</div>
<p>Java 5 introduced new language features that allow developers to
write code that is more robust whilst at the same time reducing the
amount of boiler-plate code that needs to be written. If you're new
to Java or are still using JDK 1.4, then its worth while
investigating all the new features provided in Java 5.</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e218" id="d0e218"></a>Resources</h2>
</div>
<div class="bibliomixed">
<p class="bibliomixed">Apple Java Website - <span class=
"bibliomisc"><a href="http://developer.apple.com/java" target=
"_top">http://developer.apple.com/java</a></span></p>
</div>
<div class="bibliomixed">
<p class="bibliomixed">EJB 3 - <span class="bibliomisc"><a href=
"http://java.sun.com/products/ejb/docs.html" target=
"_top">http://java.sun.com/products/ejb/docs.html</a></span></p>
</div>
<div class="bibliomixed">
<p class="bibliomixed">JAX-WS 2.0 Web Services - <span class=
"bibliomisc"><a href="https://jax-rpc.dev.java.net/" target=
"_top">https://jax-rpc.dev.java.net/</a></span></p>
</div>
<div class="bibliomixed">
<p class="bibliomixed">Sun Java Website - <span class=
"bibliomisc"><a href="http://java.sun.com" target=
"_top">http://java.sun.com</a></span></p>
</div>
<div class="bibliomixed">
<p class="bibliomixed">Xdoclet - <span class="bibliomisc"><a href=
"http://xdoclet.sourceforge.net/xdoclet/index.html" target=
"_top">http://xdoclet.sourceforge.net/xdoclet/index.html</a></span></p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
