The document summarizes several Java 5 features including generics, enhanced for loops, autoboxing/unboxing, typesafe enums, varargs, static imports, and annotations. It provides examples and explanations of each feature.
3. Generics List myIntList = new LinkedList(); // 1 myIntList.add(new Integer(0)); // 2 Integer x = (Integer) myIntList.iterator().next(); // 3 The idea behind generics is to enable the programmer to express his intention List<Integer> myIntList = new LinkedList<Integer>(); // 1 myIntList.add(new Integer(0)); //2 Integer x = myIntList.iterator().next(); // 3 – No cast required Compiler can check the type correctness at compile time. Improved readability and robustness. Introduction Cluttered Runtime error
4. Small excerpt from the definitions of the interfaces List and Iterator in package java.util: public interface List<E> { void add(E x); Iterator<E> iterator(); } public interface Iterator<E> { E next(); boolean hasNext(); } all occurrences of the formal type parameter (E in this case) are replaced by the actual type argument (in this case, Integer). Generics Defining Simple Generics
5. List<String> ls = new ArrayList<String>(); //1 List<Object> lo = ls; //2 ILLEGAL !! Line 2 is a compile time error. Generics Generics and sub typing
6. void printCollection(Collection<Object> c) { for (Object e : c) { System.out.println(e); }} Using wildcards void printCollection(Collection<?> c) { for (Object e : c) { System.out.println(e); }} Collection<?> c = new ArrayList<String>(); c.add(new Object()); // compile time error Generics Wildcards Object is not the supertype for all kinds of collections. Collection of unknown
7. public void drawAll(List<Shape> shapes) { for (Shape s: shapes) { s.draw( this ); } } drawAll() can only be called on lists of exactly Shape: it cannot, for instance, be called on a List<Circle> public void drawAll(List<? extends Shape> shapes) { ... } Generics Bounded Wildcards Shape Circle Rectangle
8. static void fromArrayToCollection(Object[] a, Collection<?> c) { for (Object o : a) { c.add(o); // compile time error }} We cannot just shove objects into a collection of unknown type. static <T> void fromArrayToCollection(T[] a, Collection<T> c) { for (T o : a) { c.add(o); // correct }} Generics Generic methods
10. FOR loop int arr[5] = {2,4,8,16,32}; for (int i=0; i<5; i++) System.out.println("Output: " + arr[i]); ENHANCED FOR loop for(int a:arr) System.out.println("Output: "+ a); // array index not required Enhanced for loop Introduction
11. Dependence on iterator List<Integer> numbers = new ArrayList<Integer>(); numbers.add(1);numbers.add(2);numbers.add(3); Iterator<Integer> numbersIterator = null; for( numbersIterator = numbers.iterator() ; numbersIterator.hasNext() ; ) { System.out.println(numbersIterator.next());; } No dependence on iterator with enhanced for loop for(Integer number : numbers) { System.out.println(number); } Enhanced for loop Collections with enhanced for loop
12. It is advantageous because It is very convenient for the programmer to iterate over a collection of elements. It has the following drawbacks :- -Step value cannot be incremented. -Backward traversal is not possible. Enhanced for loop Overview
14. Repetitive work of converting the primitive types into wrapper classes and vice - versa. Purpose of conversion is just for some API call. Auto-boxing and Auto-Unboxing enables the primitive types to be converted into respective wrapper objects and the other way around. Autoboxing / Unboxing Purpose
15. Before Java 5 int intPrimitive = intObject.intValue(); intPrimitive++; intObject = new Integer(intPrimitive); Using Java 5 Integer intObject = new Integer(10); intObject++; Autoboxing / Unboxing Introduction
16. Boolean isValid = false; // Boxing Short shortObject = 200; // Boxing if(shortObject<20){ // unboxing } ArrayList<Integer> list = new ArrayList<Integer>(); for(int i = 0; i < 10; i++){ list.add(i); // Boxing } Autoboxing / Unboxing Example
18. public static final int COLOR_RED= 0; public static final int COLOR_BLUE = 1; public static final int COLOR_GREEN = 2; This pattern has many problems, such as: Not typesafe No namespace Printed values are uninformative . Typesafe enums Previous approach
19. public enum Color { RED, BLUE, YELLOW, GREEN, ORANGE, PURPLE } The enumerated types RED, BLUE, YELLOW etc. are of type Color. Enums are full-fledged java classes and can have arbitrary methods and fields. Enums can implement interfaces. Enums can have constructors and they take arguments in the declaration as shown in the next slide. Typesafe enums Example Java.lang.Enum Color
20. public enum Color { RED(625, 740), ORANGE(590, 625), YELLOW(565, 590) //Electro-magnetic Spectrum wavelength in nm int startWavelength; int endWavelength; Color(start, end) { this.startWavelength = start; this.endWavelength = end; } public int getStartWavelength() { return startWavelength; } public int getEndWavelength() { return endWavelength; } public static void main(String[] args) { System.out.println("Red color's wavelength range, " + RED.getStartWavelength()+" ~ "+RED.getEndWavelength()); } } Typesafe enums Example Data members Constructors Methods
21. If the implementation of methods vary for each Constant, then you can implement the methods specific to a constant. public enum Color { RED { public Color complimentary() { return GREEN; }}, BLUE { public Color complimentary() { return ORANGE; }}, YELLOW { public Color complimentary() { return PURPLE; }}, ... public abstract Color complimentary(); } Typesafe enums Example
23. Int add (int a,int b,intc c); Int add (int a,int b,int c,int d); Int add (int a,int b,int c,int d,int e); Can be replaced by a single method declaration which had VAR ARGS Int add (int… numbers){ for ( int a : numbers) sum+=a; return sum; } Variable arguments Example
24. Legal: void doStuff(int... x) { } // expects from 0 to many ints // as parameters void doStuff2(char c, int... x) { } // expects first a char, // then 0 to many ints void doStuff3(Animal... animal) { } // 0 to many Animals Illegal: void doStuff4(int x...) { } // bad syntax void doStuff5(int... x, char... y) { } // too many var-args void doStuff6(String... s, byte b) { } // var-arg must be last Variable arguments Examples
28. Annotations are metadata i.e. data about data. They convey semantic information of the code to the compiler. @interface MyAnno{ String str(); int val(); } Classes , methods , fields , parameters , and enum constants can be annotated. @MyAnno(str = “Annotation example”, val=100) Public static void myMeth(){ ….. Metadata (Annotations) Introduction
29. @ClassLevelAnnotation(arg1="val1", arg2={"arg2.val1","arg2.val2"}) public class AnnotationExample { @FieldLevelAnnotation() public String field; @CtorLevelAnnotation() public AnnotationsTest() { // code } @MethodLevelAnnotationA("val") @MethodLevelAnnotationB(arg1="val1",arg2="val2") public void someMethod(String string) { // code } } Metadata (Annotations) Example
30. @Retention(retention-policy) – determines at what point an annotation is discarded. Metadata (Annotations) Retention policy @Retention ( RetentionPolicy. ) SOURCE CLASS RUNTIME Discarded by compiler Stored in class file. Discarded by JVM. Stored in class file. Utilized by JVM.
31. @interface MyAnno{ String str() default “Testing”; int val() default 9000; } Class Meta{ @MyAnno Public static void myMeth(){ Meta ob=new Meta(); try{ Class c=ob.getClass(); Method m=c.getMethod(“myMeth”); MyAnno anno=m.getAnnotation(MyAnno.class); }catch()…. Metadata (Annotations) Using reflection and default values
33. Normal Annotations — Annotations that take multiple arguments. @MyNormalAnnotation(mem1="val1", mem2="val2") public void someMethod() { ... } Single Member Annotations — An annotation that only takes a single argument has a more compact syntax. You don't need to provide the member name. @MySingleMemberAnnotation("a single value") public class SomeClass { ... } Marker Annotations — These annotations take no parameters. They are used to mark a Java element to be processed in a particular way. @Deprecated public void doWork() { ... } Metadata (Annotations) Categories
34. @Retention @Inherited @Target @Documented @Override @Deprecated @SupressWarnings Metadata (Annotations) Pre built annotations Meta Annotations