Mar 21

In this tutorial, i’ll explain most commonly used Java 5/J2SE 5.0/JDK 1.5 new features with examples.

Java 2 Platform Standard Edition 5.0 (J2SE 5.0 or Java 5 or JDK 1.5) came up with a full bunch of significant new features which are very useful for java developers as well as for JVM in order to improve performance. In this tutorial, you can find some important J2SE 5.0 new features added in JDK 1.5 which are part of day-to-day java coding.

List of most commonly used Java 5 new features:

  1. Generics for Collections
  2. Enhanced for Loop (for-each loop)
  3. Autoboxing/Unboxing
  4. Typesafe Enums
  5. Varargs/Vargs (Variable-length Argument Lists)
  6. Static Import
  7. Metadata (Annotations)
  8. Formatting
  9. Scanner

Java 5 (J2SE 5.0/JDK 1.5) New Features with Examples

1. Generics

Generics is one of the most useful features added in Java 5. It adds compile-time type safety to the Collections Framework and eliminates the necessity for type casting.

Example to show the benefits of Generics:

    import java.util.*;

    public class GenericsTest 
    {
	public static void main(String[] args) 
	{
	    List<String> names = new ArrayList<String>();
	    names.add("Ram");
	    names.add("Peter");
	    names.add("Khan");
	    names.add("Singh");
	    names.add(new Date());	// Compiler error
	    for(int i = 0; i < names.size(); i++) {
		// No need of type casting (String)
		String name = names.get(i);	
		System.out.println(" Name = " + name);
	    }
	}
    }

The above example program is written using Generics feature of Java 5. Here we are telling java compiler to accept only ‘String’ type objects for the List by using <String> thus providing compile-time type safety. Since we have declared ‘names’ as List of Strings, we need not do type casting for retrieving the elements from ‘names’. If we try to add any object other than String, java compiler shows compiler error and won’t allow us to go-ahead until we remove that black sheep object. So, in order to compile the above program you need to comment/remove the line which adds Date object. This avoids unwanted exceptions during runtime when we try to cast/use the objects stored under List. If you wanna see what does this mean, run the following code:

    List names = new ArrayList();
    names.add("Ram");
    names.add("Peter");
    names.add("Khan");
    names.add("Singh");
    names.add(new Date());	// Compiler accepts
    for(int i = 0; i < names.size(); i++) {
        // Gets Exception for Date object
        String name = (String)names.get(i);	
        System.out.println(" Name = " + name);
    }

In this old Java code, compiler accepts Date() object to be added to names List without any issue. But in runtime while retrieving that Date object, you will get the following exception:

    Exception in thread "main" java.lang.ClassCastException: 
        java.util.Date cannot be cast to java.lang.String

So, to avoid such kind of unwanted exceptions, we can use Generics to provide compile-time type safety to collections.

We can also nest generics as follows:

    Map<Integer, List<String>> mapStudents = new HashMap<Integer, List<String>>();

2. Enhanced for Loop (for-each loop)

Enhanced for loop is also referred as ‘forEach’ Loop and is specifically designed to iterate through arrays and collections.

Let’s check the benefits of enhanced for loop with the earlier Generics example program.

    import java.util.*;

    public class ForEachTest 
    {
        public static void main(String[] args) 
        {
            List<String> names = new ArrayList<String>();
            names.add("Ram");
            names.add("Peter");
            names.add("Khan");
            names.add("Singh");

            for (String name : names) {
                System.out.println(" Name = " + name);
            }
        }
    }

Here, we can simply iterate through the list ‘names’ and retrieve each element into variable ‘name’. After that, we can do whatever we want with that variable as usual. Enhanced for loop avoids the need for using temporary index variable and simplifies the process of iterating over arrays and collections.

3. Autoboxing/Unboxing

The Autoboxing feature eliminates the need for conversion between primitive data types such as int, float etc. and their respective wrapper classes Integer, Float, etc.

What is Autoboxing in Java?

The implicit automatic conversion of primitive values into corresponding wrapper class objects is known as ‘Autoboxing’.

Autoboxing Examples:

    (1)	 Integer age = 31;  // Autoboxing: 31 => Integer.valueOf(31) 

The above statement creates a new Integer object with value 31 and assigns to Integer reference variable ‘age’.

    (2)	 List<Double> weights = new ArrayList<Double>();
         weights.add(64.5);  // Autoboxing: 64.5 => Double.valueOf(64.5) 
         weights.add(73.2);  // Autoboxing: 73.2 => Double.valueOf(73.2) 

Here, two Double objects will be created with values 64.5 & 73.2 and those objects would be added to the list ‘weights’.

What is Unboxing (Auto-unboxing) in Java?

The implicit automatic conversion of wrapper class objects to primitive values is called ‘Unboxing’.

Unboxing Examples:

    (3)  if (age > 25) {  // Unboxing: age => age.intValue()
		// do something 
         }

Since age is an Integer object and we can’t perform relational operations (<, >, <=, >=) on objects, first age will be converted to ‘int’ using intValue() method of ‘Integer’ class. Later it will be compared with 25 using ‘>’ relational operator.

    (4)  double totalWeight = weights.get(0) + weights.get(1);	// 137.7
         // Unboxing: weights.get(0).doubleValue() 
         //           + weights.get(1).doubleValue()

Like in example (3), we can’t perform arithmetic operations (+, -, *, /, %) on objects, hence the two ‘Double’ objects will be converted to ‘double’ primitive values using doubleValue() method. Now, with no issues, those two double values will be added and the sum would be assigned to ‘totalWeight’.

4. Typesafe Enums

This new feature allows us to create enumerated types with arbitrary methods and fields. The standard way of representing enumerated types in java using ‘int’ has its own problems. The below example program uses standard enum types:

    public class OldEnumTest
    {
        public static final int SUNDAY = 0;
        public static final int MONDAY = 1;
        public static final int TUESDAY = 2;
        public static final int WEDNESDAY = 3;
        public static final int THURSDAY = 4;
        public static final int FRIDAY = 5;
        public static final int SATURDAY = 6;

        void printAppointment(int day) {
            System.out.println(" Please come on " + day);
        }

        public static void main(String[] args) 
        {
            new OldEnumTest().printAppointment(WEDNESDAY);
        }
    } 

    Output: Please come on 3

Here, there is no type-safety for enum values because compiler can accept any integer number for ‘int’ variable. We can’t stop somebody from passing outside range values to enum variable. For example, we can call printAppointment() method with value 10 or even -25, compiler won’t complain that this is not valid even though we are expecting a number between 0 and 6.

Another issue is that the value displayed would be a number which is not informative. By seeing that number we do not know which enum value it is referring to, moreover we do not even know that it is an enum because of the number. You can understand this better by seeing the above output.

Now consider the following type-safe enum example program:

    public class NewEnumTest 
    {
        public enum Day {
            SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
            THURSDAY, FRIDAY, SATURDAY
        }

        void printAppointment(Day day) {
            System.out.println(" Please come on " + day);
        }

        public static void main(String[] args) 
        {
            new NewEnumTest().printAppointment(Day.TUESDAY);
        }
    } 

    Output: Please come on TUESDAY

Here, compiler accepts only those values which are defined in enum ‘Day’ to be passed to printAppointment() method, thus providing compile time type-safety. Also, the output is so informative that we can understand very easily.

Hold on. It is not over. Don’t go anywhere. I have something more for you :) . Continue reading Java 5 (J2SE 5.0/JDK 1.5) New Features with Examples Tutorial 2.

Related posts:

  1. Java 5 (J2SE 5.0/JDK 1.5) New Features with Examples Tutorial 2
  2. What is Java? How to download Java (J2SE/JDK/JRE), IDE, Javadocs?
  3. Is String Mutable in Java? Why Wrapper Classes are Immutable and Final in Java?
  4. Java Wrapper Class Tutorial: Explain Java Wrapper Classes with Examples
  5. Explain Most Common Exceptions and Errors in Java with Examples
  6. What is a Java Exception? Explain Exception Handling in Java with Examples Program
  7. How to fix “Exception in thread main java.lang” Common Exceptions? – Tutorial 1
  8. Java Character Wrapper Class Tutorial: API Methods and Constructors
  9. Java Integer Wrapper Class Tutorial: API Methods and Constructors
  10. Java Primitive Wrapper Class Tutorial: API Methods and Constructors

written by Seetha Ram Janapala
Tags: annotations, auto unboxing, autoboxing tutorial, compile time type-safety, core java for beginners, core java tutorial, enhanced for loop tutorial, features added in java 5, format, generics tutorial, j2se 5.0, j2se 5.0 new features, java 2 platform standard edition 5.0, java 5, java 5 features tutorial, java 5 tutorial, jdk 1.5, metadata, nested generics, scanner tutorial, static import, String.format, typesafe enums, unboxing, varargs, vargs


4 Responses to “Java 5 (J2SE 5.0/JDK 1.5) New Features with Examples Tutorial 1”

  1. 1. Sachin Tendulkar Centuries Says:

    Nice post on Java 5 features. Very clearly explained all JDK 1.5 features. Looking for more of this kind of posts.

  2. 2. claindycreali Says:

    As good as every legacy and new-look IT vendor has its own settle on making the entire figures center more programmable via software and less dependent on specialized, proprietary and over the odds hardware.

  3. 3. website Says:

    I appreciate, cause I found exactly what I was looking for. You’ve ended my 4 day long hunt! God Bless you man. Have a nice day. Bye

  4. 4. Prefabrykaty Betonowe Says:

    It is really a great and useful piece of info. I am glad that you shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.

Leave a Reply

 
Copyright © 2014 Explain-Java.com. All rights reserved.