Way2Java

JDK 1.5 Features

Every version adds new packages and classes. JDK 1.5 version started its work under the code name Project Tiger and the version was released on September, 2004. JDK 1.5 version adds the following features to Java language. JDK 1.5 Features are programmatically very important, as often used.

Following list gives the JDK 1.5 Features
  1. Autoboxing
  2. Generics
  3. Enhanced for loop
  4. Varargs
  5. Enums
  6. Static imports
  7. C-lang printf()
  8. StringBuilder
  9. Metadata

Autoboxing – Automatic Conversion

Upto JDK 1.4, all the data structures of Java stores only objects and when retrieved returns objects. The problem is, even simple data types are to be converted into objects (using wrapper classes) and stored. The retrieved objects are to be converted back to data types to use in arithmetic operations in coding. This is a big nuisance to the programmer. This is overcome in JDK 1.5 with the introduction of autoboxing concept. Autoboxing permits to store data types directly in DS and retrieve back data types. Autoboxing is discussed clearly in data structures topic.

Generics – Type-Safe Addition

A data structure in Java accepts any data type or object as input. If only whole numbers are required to be stored, they must be validated before added to the DS. This requires extra validation code of users input. This extra code is avoided in JDK 1.5 and named as Generics. Generics allow adding one type of data only; compiler raises error if other types are added. Generics is discussed clearly in DS.

Enhanced for Loop

Generally to print the values, we take a for loop. The for loop includes initialization, test condition and incrementing/decrementing. These are avoided in enhanced for loop and this loop works in arrays and DS only. enhanced for loop is illustrated in data structures topic.

Varargs – Variable Number of Arguments

The Varargs concept permits the user to pass any number of arguments to a method depending on the requirement at runtime. The arguments are stored as an array internally. Following program illustrates.

public class VarargsTest
{
  public static void add(int... marks)                    
  {
    int total = 0;
    for(int x : marks)                                            
    {
      total += x;
      System.out.print(x + ", "); 
    }
    System.out.print(" and total is " + total + "\n");
  }
  public static void main(String args[])
  {
    add(10, 20);     
    add(10, 20, 30);     
    add(10, 20, 30, 40);     
  }
}

public static void add(int… marks)

Observe the special syntax of parameter of add() method. It takes three dots. Internally, the parameters are stored in an int array. Enhanced for loop is used to print the arguments and their total.

Enums

enum is a keyword from JDK 1.5. enum is a different flavor of a class; enum replaces class prefix. Enums are type-safe as they are by default static and final integer values. Generally enum values are written in uppercase, by convention, as they are final.

enum EmployeeSalaries
{
  HIGH, MEDIUM, LOW, POOR  
}
public class EnumTest    
{
  public static void main(String args[])
  {
    EmployeeSalaries es; 
    es = EmployeeSalaries.LOW;
 					// knowing enum value
    System.out.println("Salary of es is " + es + "\n"); 
	       				// one more value can be assigned
    es = EmployeeSalaries.HIGH;
 				         // comparing two values
    if(es == es.HIGH)
    {
      System.out.println("Employee is of high salary\n");
    }

    switch(es)                        
    {
      case HIGH:	
        System.out.println("High salary"); break;
      case MEDIUM:
        System.out.println("Medium salary");  break;
      case LOW:
        System.out.println("Low salary");  break;
      case POOR:
        System.out.println("Poor salary"); 
    }
  }
}	

switch(es)

As enum represents an integer value always, it can be used with switch statement.

Static Imports

Many methods of classes like Math and Character are static. If the variables and methods of these classes are used very often, all are must be prefixed with Math or Character which is tedious. To overcome this, the JDK 1.5 comes with static imports. With static imports, the static keyword need not be used in coding as in the following program.

import static java.lang.Math.*;
public class StaticUsage
{
  public static void main(String args[])
  {
    int radius = 10;
    System.out.println("Perimeter: " + ceil(2 * PI * radius));
    System.out.println("Area: " + floor(PI * pow(radius, 2)));
    System.out.println("Raised 3 times: " + pow(radius, 3));
  }
}

import static java.lang.Math.*;

Normal import statement imports all classes and interfaces of a package. But static import imports only static members of a single class. It avoids usage of the class name multiple times in coding. The above statement avoids Math class name to prefix every variable or method used.

ceil(), floor(), pow are the static methods of Math class and PI is a static variable. All these are used without using prefix Math name.

Supporting C-lang printf()

printf() is an extra method added to PrintStream class from JDK 1.5 version. printf() is used to print at command-prompt. The printf() uses java.util.Formatter class internally. Following program illustrates a few ways.

public class PrintfDemo
{
  public static void main(String args[])
  {
    boolean hot = false;
    char alphabet = 'A';
    int rate = 5;
    float temperature = 12.3456789f;

    System.out.printf("The boolean hot: %b", hot);                         // place holder b for boolean
    System.out.printf("\nThe char alphabet: %c", alphabet);                // c for char                
    System.out.printf("\nThe int rate: %d", rate);                         // d for int
    System.out.printf("\nThe float marks is %f", temperature);             // f for float
    System.out.printf("\nThe int value prefixed with 4 zeros: %04d", rate);// filling with zeros
    System.out.printf("\nThe float temparature is %.3f", temperature);     // precision to three decimal values
    System.out.printf("\nThe float temperature in exponential form: %e", temperature);

    System.out.printf("\n%s, %s and also %s belong to java.lang package", "System","String","Math");
    System.out.printf("\ntemperature is %4.2f", temperature); // width is 4 and precision to 2 decimal points
  }
}


The terminology used to print the values is quiet familiar to C/C++ programmers.

More on Number Formatting

Java’s capability of number formatting is far superior to C/C++. The following program illustrates.

import java.text.*;                    // for DecimalFormat and NumberFormat classes
public class FormattingDemo
{
  public static void main(String args[])
  {
    DecimalFormat df1 = new DecimalFormat("Rs 0.00");
    int rate = 25;
    System.out.println(df1.format(rate));		         //  Rs 25.00
    System.out.println(df1.format(34.45682)); 	                 //  Rs 34.46 (rounded)

    NumberFormat nf1 = NumberFormat.getInstance();
    nf1.setMinimumFractionDigits(2);  
		// gives minimum two decimal points; 0 gives no decimal part
    nf1.setMaximumFractionDigits(5);
	                                                         // gives maximum 5 decimal points
    System.out.println(nf1.format(Math.PI));                     // prints 3.14159
  }
}


The classes DecimalFormat and NumberFormat from java.text package gives more flexibility in number formatting.

NumberFormat nf1 = NumberFormat.getInstance();

NumberFormat being an abstract class cannot be instantiated directly. The static getInstance() method returns an object of NumberFormat.

nf1.setMinimumFractionDigits(2);
nf1.setMaximumFractionDigits(5);

The first statement gives two minimum decimal points and the second statement gives five maximum decimal points. They are given if required only.

High-performance StringBuilder

We know String is immutable and StringBuffer is mutable. When a string is to be manipulated in the program, it is advised to choose StringBuffer for performance reasons. But StringBuffer comes with its own demerits. StringBuffer methods are synchronized and thus allowing thread-safe operations. To overcome this, designers introduced StringBuilder with JDK 1.5 where the methods are not synchronized. Same methods of StringBuffer work with StringBuilder also. For a program and more discussion refer String topic.

Metadata and Annotations

Metadata replaces the usage of templates. Metadata is declarative programming. Annotations are useful for tool developers to generate documentation of a project.