Shashank Raj H, 10-Sept-2010 Java 5 features
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
Generics List myIntList = new LinkedList(); // 1 myIntList.add(new Integer(0)); // 2 Integer x = (Integer) myIntList.itera...
<ul><li>Small excerpt from the definitions of the interfaces List and Iterator in package </li></ul><ul><li>java.util: </l...
<ul><li>List<String> ls = new ArrayList<String>(); //1 </li></ul><ul><li>List<Object> lo = ls; //2 </li></ul><ul><li>ILLEG...
<ul><li>void  printCollection(Collection<Object> c) { </li></ul><ul><li>for  (Object e : c) { </li></ul><ul><li>System.out...
<ul><li>public void  drawAll(List<Shape> shapes) { </li></ul><ul><li>for  (Shape s: shapes) { </li></ul><ul><li>s.draw( th...
<ul><li>static void  fromArrayToCollection(Object[] a, Collection<?> c) { </li></ul><ul><li>for  (Object o : a) { </li></u...
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
<ul><li>FOR loop </li></ul><ul><li>int arr[5] = {2,4,8,16,32};  </li></ul><ul><li>for (int i=0; i<5; i++)  </li></ul><ul><...
<ul><li>Dependence on iterator </li></ul><ul><li>List<Integer> numbers = new ArrayList<Integer>();  </li></ul><ul><li>numb...
<ul><li>It is  advantageous  because It is very convenient for the programmer to iterate over a collection of elements. </...
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
<ul><li>Repetitive work of converting the primitive types into wrapper classes and vice - versa.  </li></ul><ul><li>Purpos...
<ul><li>Before Java 5  </li></ul><ul><li>int intPrimitive = intObject.intValue();  </li></ul><ul><li>intPrimitive++;  </li...
<ul><li>Boolean isValid = false; // Boxing  </li></ul><ul><li>Short shortObject = 200; // Boxing  </li></ul><ul><li>if(sho...
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
<ul><li>public static final int COLOR_RED= 0; </li></ul><ul><li>public static final int COLOR_BLUE = 1;  </li></ul><ul><li...
<ul><li>public enum Color {  </li></ul><ul><li>RED, BLUE, YELLOW, GREEN, ORANGE, PURPLE }  </li></ul><ul><li>The enumerate...
<ul><li>public enum Color {  </li></ul><ul><li>RED(625, 740),  </li></ul><ul><li>ORANGE(590, 625),  </li></ul><ul><li>YELL...
<ul><li>If the implementation of methods vary for each Constant, then you can implement the methods specific to a constant...
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
<ul><li>Int add (int a,int b,intc c); </li></ul><ul><li>Int add (int a,int b,int c,int d); </li></ul><ul><li>Int add (int ...
<ul><li>Legal: </li></ul><ul><li>void doStuff(int... x) { }  // expects from 0 to many ints </li></ul><ul><li>  // as para...
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
<ul><li>Consider the java example:  </li></ul><ul><li>Import java.lang.math.*; </li></ul><ul><li>double r = Math.cos ( Mat...
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
<ul><li>Annotations are metadata i.e. data about data. </li></ul><ul><li>They convey semantic information of the code to t...
<ul><li>@ClassLevelAnnotation(arg1=&quot;val1&quot;, arg2={&quot;arg2.val1&quot;,&quot;arg2.val2&quot;})  </li></ul><ul><l...
<ul><li>@Retention(retention-policy) – determines at what point an annotation is discarded. </li></ul>Metadata (Annotation...
<ul><li>@interface MyAnno{ </li></ul><ul><li>String str() default “Testing”; </li></ul><ul><li>int val() default 9000; </l...
Metadata (Annotations) Categories Annotations Normal  annotations Single member  annotation Marker annotations
<ul><li>Normal Annotations  — Annotations that take multiple arguments.  </li></ul><ul><li>@MyNormalAnnotation(mem1=&quot;...
<ul><li>@Retention </li></ul><ul><li>@Inherited </li></ul><ul><li>@Target </li></ul><ul><li>@Documented </li></ul><ul><li>...
Thank You !!
Upcoming SlideShare
Loading in...5
×

Java 5 Features

744

Published on

Audience: Vodafone Germany team at IBM Global Services

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
744
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
19
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Right klick on instance open context menu (access to locks, test jsps, facility to update instance or start kba)
  • Right klick on instance open context menu (access to locks, test jsps, facility to update instance or start kba)
  • Java 5 Features

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

      Clipping is a handy way to collect important slides you want to go back to later.

    ×