Java 5 features

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Java 2 Standard Edition 5.0 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. We are going to have an overview of the features like below.

List of Java 5 features:

  • Generics
  • Enhanced for Loop (for-each loop)
  • Autoboxing/Unboxing
  • Typesafe Enums
  • Varargs/Vargs (Variable-length Argument Lists)
  • Static Import
  • Metadata (Annotations)
  • Formatting
  • Scanner
  • Covariant Return Type
  • Garbage Collectors
  • Java Concurrent package

Generics

Generics provide a way to create and use type safe data structures. This means that no longer do you have to create a List of the basic Objects then typecast every time you pull objects out

Example of Generics

import java.util.*;

public class GenericsMain {
 public static void main(String[] args) 
 {
 List<String> cities = new ArrayList<String>();
 cities.add("Roorki");
 cities.add("Saharanpur");
 cities.add(new Date());// Compiler error here
 for(int i = 0; i < cities.size(); i++) {
 // No need of type casting (String)
 String city = cities.get(i);	
 System.out.println(" City = " + city);
 }
}
}

This above example program is written using Generics feature. Here java compiler to accept only `String` type of objects for the List by using <String> and provide compile-time type safety because you have declared `cities` as List of Strings so you do not need to do type casting for retrieving the elements from `cities`. If you try to add any object other than String, java compiler shows compiler error and won`t allow adding this object. If you compile the above program you need to comment or remove the line which adds Date object.

In pre-java 5, the method that get objects out from collection could have only one kind of return type java.lang.Object. If you want to get element from String list, you require a cast to do like below.

.
import java.util.*;

public class GenericsMain {
 public static void main(String[] args) 
 {
 List cities = new ArrayList();
 cities.add("Roorki");
 cities.add("Saharanpur");
 for(int i = 0; i < cities.size(); i++) {
 // No need of type casting (String)
 String city = (String)cities.get(i);	
 System.out.println(" City = " + city);
 }
}
}
      Advertisements