Java Reference
In-Depth Information
The enhanced for loop allows this to be simplified, as shown here:
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
Note that the new for loop can't be used in every scenario. In particular, it hides the itera-
tor, so you can no longer call any methods on the iterator that might change the underlying
collection.
The formatting rule for the new for loops is to have a space before and after the colon.
Autoboxing
JDK 5 allows for automatic type conversions between primitives and their wrapper classes.
For example:
Integer myInteger = 5; // automatically converts 5 (int) into an Integer
No special coding convention is needed for handling this.
VarAgs
Variable argument lists (also commonly referred to as VarArgs) allow the coder to specify that
the number of arguments in a constructor or method signature is variable. Using this facility
can reduce the number of overloaded methods and constructors.
However, VarArgs come at a price: when you specify the exact number and type of para-
meters a given method requires, the Java compiler can perform type checking to ensure that
your usage of the method is correct. When you use VarArgs, only minimal checking is possible.
To give an example, consider creating a class Dog , which has two optional attributes
(fields): age and name . If you wanted to create constructors that can handle all potential ways
that a user could create a Dog class, you would need the following constructors:
Dog();
Dog(int age);
Dog(String name);
Dog(int age, String name);
Unfortunately, it doesn't end there. The number of constructors you need is 2 to the
power of the number of parameters. So if the Dog class has the following seven attributes— age ,
height , weight , name , owner , color , and pedigree —we would potentially need 128 constructors
to allow for every combination!
We would then have additional problems, because Java would be unable to differentiate
between constructors where the method signatures are effectively the same. For example:
Dog(int age, String name);
Dog(int age, String owner);
Search WWH ::




Custom Search