Back to Article

Java Language Enhancements

by Benoy Jose

Introduction

The Java language is already powerful enough in many aspects, but it does not hurt to add a few more features that would make it more powerful and programmer friendly. With the advent of Microsoft’s Microsoft.net, Sun has been under enormous pressure to enhance the Java language and make it more programmer friendly. Though the Java community is against major changes to the language, the pressure has been on to add few features that were inherently missing in Java. A major slew of features like those in Microsoft.net would make Java less flexible, so Sun has carefully chosen a few features that already existed in languages like C and C++, but were left out in the original Java specification. Keeping this in mind Sun and its partners have proposed a set of enhancements to the Java language through the Java specification request JSR 201. The proposed enhancements are as follows:

  • An enhanced "for loop" that would allow easier iteration over collections.
  • An automatic conversion mechanism to convert primitive types to their corresponding wrappers and vice versa.
  • A new syntax for an enumerated type
  • A static import.
  • Variable-Arity Methods.

These proposed enhancements have been included into the J2SE 1.5 tiger edition which is presently in the beta 1 stage.

 

Enhanced For Loop:

The "for loop" is a very powerful construct when dealing with simple loops. But when it comes to a collection of string values it becomes worse. Take the sample below all the elements of this ArrayList are Strings yet we need to specify the cast each time an element is retrieved. Well I am not implying that the collections framework design is flawed. The idea of collections to include any object makes it truly object oriented but this feature brings in an additional burden of checking and converting objects each time they are stored in a collection. The enhanced "for loop" makes the iteration through collections easy while maintaining the integrity of the language.

 
int [] intArray = new int[10];
for (int i=0; i< 10; i++){
	System.out.println (“Value at ”+I + “ is ”+intArray[i]);
} 
ArrayList  arrayList = (ArrayList) someColl;
for (int i =0; I < arrayList.size(); i++){
	String tempString = (String) arrayList.get(i);
}

	How about this  
for  (String tempString : someColl ){
	
}

In this example tempString is some String where the value is held and someColl is a collection of type java.util.Collection. The above piece of code is an example of the new enhanced "for loop"’ proposed by the JSR 201. The enhanced "for loop" makes it easier to iterate through collections and Arrays while making code simple and more readable. The enhanced "for" uses the existing "for" keyword with some modifications so that the virtual machine is left undisturbed. The enhanced "for" construct is accommodated by modifying the compiler and these changes do not affect existing programs in any way. To make this possible a new interface called the java.lang.Iterable is being introduced. Any collection that can be used in the enhanced "for loop" needs to be an instance of the Iterable interface. For the coexistence with the existing Collections framework the java.langCollection interface will be retrofitted to implement or extend the Iterable interface.

The enhanced "for loop" assumes that the elements contained in the collection are of the same type. If this assertion is false an improper assignment exception is thrown. Additionally the enhanced "for loop" acts more like an enhancement to the "Iterator" interface. The enhanced for loop has some drawbacks as it does not allow the user to modify or delete elements in a collection as an iteration is being done. This is more on the lines of what the java.util.Iterator does, the enhanced "for loop" actually moves through the collection and exhausts it as it finishes through it, but this does not mean that the collection is exhausted or deleted, the rules that apply for the Iterator apply for the enhanced "for loop". The enhanced "for" also does not allow simultaneous iterations over multiple collections. A sample of a HashMap is given below:

 HaspMap myMap = someHashMap;
 for (Map.Entry<String, String> e : myMap.entrySet()){
 System.out.println ("Key "+ e.getKey() + " Value "+ e.getValue());
}

Autoboxing:

The Java language inherited a major part of its language semantics from C which allowed for primitive types to be included into Java. Primitives are very helpful as they increase speed, efficiency and bring them closer to real life numbers. This facility comes at the expense of object orientation as these primitives are not classes. The collections framework was created with object orientation in mind; hence they work only with objects. As a result of this programmers have to go through the trouble of converting primitive types to their respective wrapper objects so that they can be stored in collections. The reverse process of converting from a wrapper to the primitive needs to be done as real life computations are done on primitives rather than on objects. This introduces a lot of unnecessary conversions and checks that make programs huge.

The new changes propose a new Autoboxing technique that would allow automatic conversion of primitives into their corresponding wrapper types. The change reduces unnecessary casts while converting primitives to their corresponding wrappers.

Boxing allows int values to be converted into Integer objects, the other primitive types included in boxing are byte, char, short, long, float and double. The reverse process of unboxing allows wrapper objects to be converted into their corresponding primitive values.

Earlier to the proposal "for loops" , "while loops" and "do while loops" only accepted primitive values within them making it difficult for primitive wrapper objects to be used in the loops. The autoboxing technique fixes the problems and allows wrapper objects to be used in these loops. So a while statement can now take a Boolean or a boolean expression and evaluate it, while a "for loop" can take Integer arguments and int arguments. In the same way, bit wise operations, arithmetic operations and logical operations that could only be done previously on primitive data types can now be done on wrapper objects.

Typesafe Enumerations:

The new JSR enhancement proposes to include a C style enumeration to increase the power and performance of Java. The enhancement is inspired from the Enum pattern described in the book "Effective Java Programming Language Guide". The Enum provides compile time type safety and performance comparable to primitive constants. It provides a namespace for each enum type so that class name prefix need not be included with each constant name. Moreover the Enum provides flexibility to add, remove or modify constants without recompiling Clients. It also provides flexibility to add arbitrary fields to an Enum and allows them to be used with the Collections framework.

An enum is a special type of class that has members that are public enum constants. All enum classes are serializable, comparable and non cloneable so that comparison and serialization operations are automatically taken care of. A sample of a enum would be:

public enum Months {January, February March, April, May, June, July,… }

The new Enumeration is proposed as a new class called Enum that will be included into the java.lang package and all Enum implementation classes will have to subclass themselves from this Enum class. Additionally an EnumSet and EnumMap implementations are being added to the java.util package to enhance the power of the collections framework.

All Enum classes are implicitly final with a few rare exceptions. Enum classes cannot be instantiated using the new operator. Constructors are not allowed to chain to a super class constructor, however an Enum class constructor may chain with other enum constructors.

      public enum Months {
      	January(1), February(2), March(3)
      	Months (int value){
      	this.value = value;
      }
      private final int value ;
      public int value(){
      	return value;
      }
      }
The syntax of the switch statement is extended to include enum constants. 
      switch (Months){
      	case Months.January:
      		return 1;
      	case Months.March
      		return 3; 
      } 

The proposed enhancement makes no changes to the JVM and is implemented in the Java language by the inclusion of a few libraries. It also works seamlessly with the other enhancements like the static import and enhanced "for loop".

Static Import:

Java provides a number of static utility methods like parseInt(), abs, sqrt etc that can be used to do mathematical and other logical operations. These methods are provided as static methods so that an explicit instantiation is not required to use them. Additionally programmers use constants as static final variables so that they can be used across the whole applications without instantiation. The way these variables are accessed can be made easy by omitting the class name as the class name identifier is many times redundant.

The new static import proposes a similar addition called static imports where the import statement is modified to import static methods and fields just like classes are imported. This makes it easy for mathematical and other standard operations provided in Java to be accessed directly without the class name. It also makes it easier to import constants and use them directly in the code with out the class modifiers. If the above mentioned enum is also included in the Java spec then enums can be directly accessed without the enum name.

The proposed declaration would look like this

	import static java.lang.Math ;
	import static mypackage.ProjectConstants; 
	import static Seasons;
	
      int a= Math,max(Seasons.January ,Integer.parseInt("5") ); 
      can be replaced by 
      int a = max (January, parseInt("5"));

The method max is part of the Math package and January and March are declared in an Enum class defined in the Enum section of this article.

The keyword static is redundant here as the compiler would obviously know that the imported file has constants or static methods. It has been included into the declaration so that it is clear to the programmer that the imported file is a constant rather than an application class file.

The static import only works for static methods and variables and cannot be used to import instance variables of classes.

To avoid name clashes two static import declarations with the same name would throw a compilation error. However if two static import declarations point to the same class, then one of them is ignored as duplicate.

Variable-Arity Methods (Varargs):

The JSR proposes to introduce variable length argument list methods to the Java language. The affect of this can be felt in applications that use a lot of internalization in their code. Presently Java allows a fixed length argument list which is used in methods like java.text.MessagingFormat.format() to format messages. The new proposal introduces a variable length argument list that can be used to pass in multiple values for internalization purposes.

Conclusion:

The JSR 201 has proposed a wide range of enhancements to the Java language to make it more effective than it already is. They are taking special care to make sure that these changes do not affect existing programs and doing their best to make them backward compatible. The changes do not affect how the JVM behaves and are mostly taken care of by changes to the compiler and in some cases by additional library support. Sun has carefully steered away from adding keywords like it did when it introduced assertions in the Java language. The new specification is in the public review stage where input from programmers like you are solicited. Many discussions boards are already discussing these changes. It would probably be a good idea to start off a thread here at JavaBoutique 's Forums and discuss the implications these enhancements have on the Java language. This could go a long way in contributing the input of programmers to help shape the future of Java.

More Information:

The JSR 201 home page is http://jcp.org/en/ jsr/detail?id=201. The J2SE 1.5 is in the beta 1 stage as of now and most of these enhancements are already included into the specification.


Benoy Jose is a web developer with over six years of experience in J2EE and Microsoft technologies. He is a Sun Cetified programmer and enjoys writing technical and non-technical articles for various magazines.


Back to Article