Java & J2EE Page 5 - Java Comes of Age |
Auto-boxing/Auto-Unboxing The idea of auto-boxing and auto-unboxing is to make it easier to convert between primitive data types, like int and boolean, and their equivalent Classes, like Integer and Boolean. It is sometimes frustrating to have to do such a conversion, especially if the purpose of the conversion is just for a method call, after which the results must be converted back to their original form again. For example, this feature allows you to write the following:
Previously, this would have generated the following error:
With Java 1.5, however, the Booleans are automatically converted to booleans before the && operator is applied. The next example shows ints automatically being converted to Integers to store on a Stack, then automatically being converted back again to perform the addition and store the result in the variable stackSum.
VarArgs Another new feature is the ability to define methods that accept a variable number of arguments. For example:
In a sense, this is syntactic sugar, because the formal parameter to the method is just an array. On the other hand, this is exactly what you would need for a conventional formatted print method, like the printf statement of C. And indeed, Java 1.5 does include such a method! The printCards method above can be rewritten as:
Here, the printCards method accepts a variable number of arguments and the printf method call also uses a VarArgs method call. The %s in the format control string indicates that a value should be inserted at that point, and the following strings are the strings to be inserted.
blog comments powered by Disqus |