The Tiger feature list is defined in JSR-176 (J2SE 5.0 (Tiger) Release Content), which serves as an umbrella JSR that only lists APIs defined in other component JSRs. Please see JSR-176 for details about the component JSRs.
..
Generics
To the Most Despised Collection 'Castwe'll Bid A Fond FondWell At Lastwith Generics' Burning Sperthe Need for Cast Will Disappear
The Collection interface, which is implemented by all collection classes, suggests that all concrete collections are collections of Objects at runtime. This places a burden on the developer of the calling class by forcing him to know the actual type of the elements in the collections, that can be accomplished by looking at the API or using the reflection API As an example, consider the following class, Ex1, which creates a collection of two strings and one integer, and then prints out the collection.:
EX1.java
Import java.util. *;
Public class ex1 {
Private void testcollection () {
List list = new arraylist ();
List.add (New String ("Hello World!");
List.add (New String ("Good Bye!"));
List.add (New Integer (95));
PRINTCOLLECTION (LIST);
}
Private Void PrintCollection (Collection C) {
Iterator i = C.Iterator ();
While (I.hasNext ()) {
String item = (string) i.next ();
System.out.println ("Item:" item);
}
}
Public static void main (String Argv []) {
EX1 E = New EX1 ();
e.TestCollection ();
}
}
The problem here is that an explicit cast is required in the printCollection method This class compiles fine, but throws a CLassCastException at runtime as it attempts to cast an Integer to a String:. Item: Hello world!
Item: Good Bye!
Exception in thread "main" java.lang.classcastexception: java.lang.integer
AT EX1.PRINTCOLLECTION (ex1.java: 16)
AT EX1.TestCollection (ex1.java:10)
AT EX1.MAIN (ex1.java:23)
GENERICS, WHICH ARE ALSO KNOWN AS Parameterized Types, Provide Compile-Time Typesafety for Collections and Eliminate The Drudgery of Casting. Using Generics, The Ex1 Class Above Can Be Written As Follows:
EX2.java
Import java.util. *;
Public class ex2 {
Private void testcollection () {
List
List.add (New String ("Hello World!");
List.add (New String ("Good Bye!"));
List.add (New Integer (95));
PRINTCOLLECTION (LIST);
}
Private Void PrintCollection (Collection C) {
Iterator
While (I.hasNext ()) {
String item = i.next ();
System.out.println ("Item:" item);
}
}
Public static void main (String Argv []) {
EX2 E = New EX2 ();
e.TestCollection ();
}
}
Now, if you try to compile this code, a compile-time error will be produced, informing you that you can not add an Integer to a collection of Strings. Therefore, generics enable more compile-time type checking and therefore mismatch errors are caught at Compile Time Rather Than at runtime.
You may have already noticed the new syntax used to create an instance of ArrayList (ie List
// ...
}
Here E Is A Type Variable, Which IS An Uqualified Identifier. IT Simply Acts as a placeholder for a type to be defined when the list is used.
Java generics vs. C Templates
While generics look like the C templates, it is important to note that they are not the same Generics simply provide compile-time type safety and eliminate the need for casts The main difference is encapsulation:.. Errors are flagged where they occur and not later at some use site, and source code is not exposed to clients. generics use a technique known as type erasure as described above, and the compiler keeps track of the generics internally, and all instances use the same class file at compile / run time.
A C Template on The Other Hand Is Just A Fancy Macro Processor; WHENEVER A TEMPLATE CLASS, The Entire Code for the New Class.
ENHANCED for loop
While Iterators Have The Their Usesthey Sometimes Strangle US Like Nooseeswith Enhanced-For's Deadly Rayiterator's Kept At Bay
The current for statement is quite powerful and can be used to iterate over arrays or collections. However, it is not optimized for collection iteration, simply because the iterator serves no other purpose than getting elements out of the collection. The new enhanced for construct lets You Itere Collection and Arrays WITHOUT Using Iterators or Index Variables.The New Form of The for Statement Has The Following Syntax:
For (FormalParameter: Expression) Statement
Note that Expression must be an array or an instance of a new interface called java.lang.Iterable, which is meant to ease the task of enabling a type for use with the enhanced for statement. This means that the java.util.Collection now Extends The Iteeable Interface That Has The Following Signature:
Package java.lang;
Public Interface ITERABLE
/ **
* Returns An Iterator Over The Elements in This Collection.
* There is no guarance the Elements in Which the elements
* Are returned (unsS this collection is an instance of some class
* That provides such a guarance).
*
* @Return An Iterator Over The Elements in this Collection
* /
Iterator
}
AS An Example, Consider The Following Method That Uses The Conventional For Statement To Iterage Over a Collection:
// AssuMe We Have an Instance of StringBuffer "SB"
Public void oldfor (Collection C) {
Iterator i = c.iterator (); I.hasnText ();) {
String str = (string) i.next ();
Sb.append (str);
}
}
With the addition of generics, The Above Segment of code Can Be Rewritten Using The Enhanced for Statement As Follows:
// AssuMe We Have an Instance of StringBuffer "SB"
Public void newfor (Collection
For (String str: c) {sb.append (str);
}
}
MUCH CLEANER, EH?
THE ENHANCED for Statement Can Be Used to Iteerate Over An Array. Consider The Following Segment of Code for a Method That Calculates The Sum of The Elements in an Array:
Public int sumarray (int arch ") {
INT SUM = 0;
For (int i = 0; i SUM = array [i]; } Return SUM; } Using the enhanced for Statement, this Can Be Rewritten As: Public int sumarray (int arch ") { INT SUM = 0; For (INT I: Array) { SUM = I; } Return SUM; } The new for statement, however, is not a replacement for counting for loops for arrays Sometimes, the index variable serves more than just an array index -.. When a different traversal order is needed, for example In addition, the enhanced for construct IS a compiler 'trick' and can activually end Up Being Slower WHEN USED For Large Collectes. Many Developers Are Asking Why They Didn't Add The Foreach and in So That We Can Write: Foreach (Element in Collection) The fact of the matter is that adding new keywords to a language such as Java is quite costly. In addition, it would not be compatible with existing source code that uses the in keyword, for example, as in System.in. So the Whole IDEA IS Just to Keep Things Upwardly-Compatible. Autoboxing / unboxing When From The Collections INTS Are Drawnwrapper Classes Make Us Mournwhen Tiger Comes, We'll Shed No Tearswe'll Autobox The M Manual conversion between primitive types (such as an int) and wrapper classes (such as Integer) is necessary when adding a primitive data type to a collection As an example, consider an int being stored and then retrieved from an ArrayList.: List.add (0, New Integer (59)); int N = ((Integer) (List.get (0))). INTVALUE (); The New Autoboxing / Unboxing Feature Eliminates this Manual Conversion. The Above Segment of Code Can Be Written As: List.add (0, 59); INT TOTAL = list.get (0); However, Note That The Wrapper Class, Integer for Example, Must Be Used As a Generic Type: List Programming language critics may have a lot to say about the autoboxing / unboxing feature. On one hand, Java developers agree that the distinction between primitive data types and references can be burdensome. In a pure object-oriented language there should be no difference between a primitive data type and a reference, as everything is an object The other issue is that of identity:. many think of primitive data types as entities that represent mathematical values, which are different from references. ............ .. TypeSafe Enumerations THE INT-ENUM WILL SOON Be Gonelike a Foe Weame Known Too Long.with Type-Enum's Mighty Powerour Foe Will Bother US No More No More An enumerated type is a type whose values consist of a fixed set of constants. The C-style enumerated type, enum was omitted from the Java programming language. A commonly used pattern for enumerated types in Java is to define a class of constants as follows : Public class mainmenu { Public static final int menu_file = 0; Public static final int menu_edit = 1; Public static final int menu_format = 2; Public static final int menu_view = 3; } This Pattern Has Several DrawBacks include: It is not type safe Constants are compiled into clients and therefore adding more constants require recompilation of the clients It has no namespace and therefore must prefix constants Provides no easy way to translate the constants into informative printable values In addition to the above, and as we all know, an object is an instance of a class. An object has state (represented by variables) and behavior (represented by methods). The above MainMenu class has state only. So from an object -ORIENTED POINT OF VIEW, IT IS Not Really a class Since ITS Instances Or Objects Would Have No Behavior. A type safe enum pattern that avoids all of the above problems has been proposed by Joshua Bloch in his book "Effective Java Programming Language Guide" The idea is to define an enum as a class that represents a single element of the enumerated type;. Such a class must not provide public constructors. Here is an example: Public class mainmenu { PRIVATE FINAL STRING NAME; Private mainmenu (String name) { THIS.NAME = Name; } Public Static Final MainMenu File = New Mainmenu ("file"); Public Static Final MainMenu Edit = New Mainmenu ("Edit"); Public static final mainmenu format = new mainmenu ("format"); Public Static Final MainMenu View = New Mainmenu ("View"); Public string toString () { Return Name; } } Using MainMenu, there is no way for a client to create an object of the class or extend it This is a compile-time typesafe enumerated type:. It is guaranteed that if you declare a method with a parameter of type MainMenu, then any non -null object reference passed in represents one of the four valid menu items. Any attempt to pass an incorrectly-typed object results in a compile-time error. in addition, this is a truly object-oriented class as it contains both state and behavior J2se 5.0, HoWever, you do not need to worry About Inventing your OWN Enumeration Patterns Since IT Provides a TypeSafe ENUMERATED TYPE FACILITY. The J2SE 5.0 Enum Declaration Looks As Follows: Public enum mainmenu {file, edit, format, view}; This syntax looks much like enums in other languages such as C / C , but in C / C enums are simply glorified integers where in Java a full-fledged class is generated for each enum type This approach has many advantages including.: It provides strong compile-time type safety It provides a separate namespace for each enum type and thus eliminates the need to include a prefix in each constant name Constants are not compiled into clients so you can freely add, remove, or reorder them without recompiling the Clients Printed Values Are Informative Instead of Just NumBers Enum Conntants Can Be Used Where There Are A Couple of Important Things To Note About Enum Declarations. AS An Example, Consider The Following Declaration: Public enum mainmenu {file, edit, format, view}; The word enum is reserved and therefore if you have been using it as an identifier, you should adjust your code when compiling with a J2SE 5.0 compiler. The above enum declaration generates a class (MainMenu in the above example), which automatically implements the Comparable Here is a completion and then declares an enumeration and then prints the value: Public class example { Public enum mainmenu {file, edit, format, view} Public static void main (string [] argv) { MAINMENU MENU: MainMenu.Values ()) System.out.println (menu); } } And the Following Segment of Code Shows Another Example Using The Switch Statement: MAINMENU MENU: Mainmenu.Values ()) { Switch (menu) { Case file: System.out.println ("File Menu"); Break; Case Edit: System.out.println ("Edit Menu"); Break; Case Format: System.out.println ("Format Menu"); Break; Case View: System.out.println ("View Menu"); Break; } } It is worth noting that two classes have been added to java.util in support of enums: EnumSet (a high-performance Set implementation for enums; all members of an enum set must be of the same enum type) and EnumMap (a high- Performance Map Implementation for Use with enum keys). Static imports And from the constant interfaceweweed inherit no disgracewith static import aturiful j will be unqualified The static import feature enables you to import static members from a class or an interface and thus use them without a qualifying name As an example, consider the following interface that contains two constant values:. Package com.name; Interface xyz { Public static final double constant1 = somevalue; Public Static Final Double constant2 = anothervalue; } Now, The Constants In The XYZ Interface Can Be Used As Follows: Public class myclass ustements xyz { .... Double value = 2 * constant1; ... } As you can see, a class must mailment the interface in Order to have access to the constants defined in the interface. In J2SE 5.0, Static Import Solves This Problem as shown in the folloading example: Import static com.name.xyz. *; Public class myclass { ... Double value = 2 * constant1; ... } As Another Example, Consider The Following Static Imports: Import static java.lang.math. *; Import static java.lang.system. *; With these two static imports, you now can use sin (x) instead of math.sin (x), and out.println ("hello there"); instead of system.out.println ("Hello there") ;. Metadata As for Noble Metadatai'll Have To Sing Its Praises Laterits Uses Are So Numerousto Give The Bus The J2SE 5.0 metadata feature is a facility that allows developers to annotate their code so that tools can generate boilerplate code (eg stub generation to remote procedure calls) as directed by annotations. This facility allows for parsing of your Java files and generating artifacts such as XML Descriptors Or Source Code. For More Information, Please See A metadata facility for the java programming language. Others In Adducts and Features, Several Other Enhancements Have Been Introduces, this section section section section section section section section section section section section section section section section section section section section O Joyless Nights, o Joyless Daysour Program CLUTTERED with arrayswith; wee ne't white; we'll simply put the args inline The Variable Arguments New Functionality In J2se 5.0 Allows Multiple Arguments to Be Passed As PARAMES To Methods As: Void SomeMethod (Object ... args) { // do something } // invoke the method SomeMethod ("Arg1", "Arg2", "Arg3"); The noteation ... Is Required. The Printf Statement, WHICH IS Discussed Later, IS An Example of Useing Variable Arguments. Formatted Output: The variable arguments functionality has been used to implement the flexible number of arguments required for printf That is right J2SE 5.0 provides C-like printf functionality, so now it is possible to easily format output using printf.!: System.out.printf ("% s% 3d", name, agen Enhanced Input: Prior to J2SE 5.0, in order to read an integer value from the keyboard, it has to be read as a String and then parsed as follows (this code does not include the try and catch constructs): BufferedReader Br = New BufferedReader (NEW INPUTSTREADER (System.in); String str = br.readline (); INT n = integer.parseint (STR); In J2se 5.0, The Java.util.scanner Class Can Be Used to Accomplish The Same Thing But with Less Code As Follows: Scanner reader = new scanner (system.in); INT n = reader.nextint (); .................. .. If you need to process more complex input, use the java.util.Formatter class, which includes pattern matching algorithms.Synchronization: J2SE 5.0 provides higher-level synchronization constructs in the form of a comprehensive library of concurrency utilities (java.util.concurrent ) containing thread pools, queues, concurrent collection, special purpose locks, and barriers. This is a substantial addition that will change the way we develop concurrent Java applications. Stay tuned for an article that explains this new functionality.