In this article, we will discuss several new language features in JDK1.5, including:
Generics: Provides the type security during compilation for collections. You do not need to obtain an object from Collections to perform forced conversion (cast)
Enhanced for loop-reduces potential errors of the iterator (error-proneness)
Autoboxing/unboxing-you do not need to manually convert between the basic type (primitive types) (such as double) and wrapper types (such as Double.
Type-safe enumeration (Typesafeenums)-provides various benefits of the Type-safe enumeration mode.
Static import-you do not need to prefix the Class Name of the Static member variable of other classes. This makes the code more concise.
Metadata prevents programmers from writing boiler plate code and provides the opportunity to design declarative programs ).
Let's discuss each new feature in detail and look at some examples.
Generic)
Generic is one of the coolest features in JDK1.5. By introducing generics, we will be able to get the possibility of throwing ClassCastExceptions in a less secure and runtime manner during compilation. In JDK1.5, you can declare the type of the object to be received/returned by a set. In JDK1.4, creating a List of employee names requires a collection object, as shown in the following statement:
List listOfEmployeeName = new ArrayList ();
In JDK1.5, you will use the following statement
List listOfEmployeeName = new ArrayList ();
The coolest thing is that if you try to insert a non-string value, you will find and fix this type of problem during compilation. If there is no generic type, you will find such a bug. When your customer calls it, it will tell you that the program you write throws a ClassCastException and crashes.
In addition, when you get an element from the set, you do not need to perform forced conversion. It was originally:
String employeeName = (String) listOfEmployee. get (I ));
The following statement is simpler than the preceding one:
String employeeName = listOfEmployee. get (I );
It is unreasonable to forcibly convert an object because it is not clear about the object type, and more importantly, it will fail at runtime. If you accidentally input a set that contains the string buffers type rather than the string type, what will happen. In Listing A, the customer is required to input A strings type set that cannot be forced by the compiler. Listing B shows how the same method is implemented using generics.
Listing
StaticbooleancheckName (Collection employeeNameList, String name ){
For (Iteratori = employeeNamList. iterator (); I. hasNext ();){
String s = (String) I. next ();
If (s. equals (name )){
Return true;
// Print employee name here ......
}
}
Return false;
}
Listing B
StaticbooleancheckName (Collection employeeNameList, String name ){
For (Iteratori = employeeNamList. iterator (); I. hasNext ();){
If (I. next (). equals (name )){
Return true;
// Print employee name here ......
}
}
Return false;
}
Now, the method signature clearly shows that the input set must only contain strings. If you try to input a collection containing string buffers, the program will not compile. Note that this method does not contain any forced conversion. It only needs one line. Once you get used to generics, it is clearer.
Enhanced For Loop
The For loop syntax in the current JDK version is as follows:
Void printAll (Collection c ){
For (Iteratori = c. iterator (); I. hasNext ();){
Employee emp = (Employee) I. next ();
System. out. println (emp. getName ());
}
}
Now, use the enhanced For statement to implement the same method:
VoidprintAll (Collection c ){
For (Object o: c)
System. out. println (TimerTask) o). getName ());
}
In this type of For loop, you should think of ":" as "in", so in this example, you can think of "for Object o in c ". You can find that this For loop is more readable.
Automatic Placement/Automatic Retrieval (Autoboxing/unboxing)
Java has basic data types and packaging classes around these basic data types. In general, programmers need to convert one type to another. Look at the code snippet in Listing C.
Listing C
Public class Employee {
Private static final Integer CHILD = new Integer (0 );
Public static void main (String args []) {
// Code for adding n to an Integer
Int n = 10;
Integer age = new Integer (30 );
Integer ageAfterTenYear = new Integer (age. intValue + 10 );
}
}
Note how messy the inner loop code used to calculate ageAfterTenYear looks. Now, in Listing D., let's see what the same program looks like after it is rewritten using autoboxing.
Listing D
Public class Employee {
Public static void main (String args []) {
Int n = 10;
Integer age = new Integer (30 );
Integer ageAfterTenYear = age + 10;
}
}
One thing worth noting: In the past, if you took out the (unbox) Null value, it would change to 0. In the code, the compiler will automatically convert Integer to int, add 10, and then convert it back to Integer ..
Type-safe enumeration (Typesafeenums)
Type Security enumeration provides the following features:
They provide type security during compilation.
They are all objects, so you do not need to put them into the collection.
They are implemented as a type, so you can add some methods.
They provide a suitable namespace for the enumeration type.
Their printed values are informative-if you print an integer enumeration (intenum), you only see a number, and it may not be intelligence.
Example 1:
Enum Season {winter, spring, summer, fall}
Example 2:
Public enum Coin {
Penny (1), nickel (5), dime (10), quarter (25 );
Coin (int value) {this. value = value ;}
Private final int value;
Public int value () {return value ;}
}
Static import)
Static import makes the code easier to read. Typically, you need to use a constant (constants) defined in another class, like this:
Importorg. yyy. pkg. Increment;
Class Employee {
Public Double calculateSalary (Double salary {
Return salary + Increment. INCREMENT * salary;
}
}
When static import is used at that time, we can use these constants without having to prefix the class name for the constant name, like this:
Import static org. yyy. pkg. Increment;
Class Employee {
Public Double calculateSalary (Double salary {