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.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
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
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
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
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
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
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
FOR loop int arr[5] = {2,4,8,16,32};  for (int i=0; i<5; i++)  System.out.println(&quot;Output: &quot; + arr[i]);  ENHANCED FOR loop for(int a:arr) System.out.println(&quot;Output: &quot;+ a); // array index not required Enhanced for loop Introduction
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
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
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
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
Before Java 5  int intPrimitive = intObject.intValue();  intPrimitive++;  intObject = new Integer(intPrimitive);  Using Java 5  Integer intObject = new Integer(10);  intObject++;  Autoboxing / Unboxing Introduction
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
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
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
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
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(&quot;Red color's wavelength range, &quot; + RED.getStartWavelength()+&quot; ~ &quot;+RED.getEndWavelength()); } }  Typesafe enums Example Data members Constructors Methods
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
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
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
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
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
Consider the java example:  Import java.lang.math.*; double r = Math.cos ( Math.PI  *  theta ); More readable form: Import static java.lang.math.PI; Import static java.lang.math.cos; double r = cos ( PI  *  theta );   Static import Example
Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
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
@ClassLevelAnnotation(arg1=&quot;val1&quot;, arg2={&quot;arg2.val1&quot;,&quot;arg2.val2&quot;})  public class AnnotationExample {  @FieldLevelAnnotation()   public String field;   @CtorLevelAnnotation()  public AnnotationsTest() {  // code }  @MethodLevelAnnotationA(&quot;val&quot;)  @MethodLevelAnnotationB(arg1=&quot;val1&quot;,arg2=&quot;val2&quot;)  public void someMethod(String string) {  // code }  }  Metadata (Annotations) Example
@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.
@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
Metadata (Annotations) Categories Annotations Normal  annotations Single member  annotation Marker annotations
Normal Annotations  — Annotations that take multiple arguments.  @MyNormalAnnotation(mem1=&quot;val1&quot;, mem2=&quot;val2&quot;)  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(&quot;a single value&quot;)  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
@Retention @Inherited @Target @Documented @Override @Deprecated @SupressWarnings Metadata (Annotations) Pre built annotations Meta Annotations
Thank You !!

Java 5 Features

  • 1.
    Shashank Raj H,10-Sept-2010 Java 5 features
  • 2.
    Topics Generics Enhancedfor Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 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 fromthe 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
  • 9.
    Topics Generics Enhancedfor Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 10.
    FOR loop intarr[5] = {2,4,8,16,32}; for (int i=0; i<5; i++) System.out.println(&quot;Output: &quot; + arr[i]); ENHANCED FOR loop for(int a:arr) System.out.println(&quot;Output: &quot;+ a); // array index not required Enhanced for loop Introduction
  • 11.
    Dependence on iteratorList<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
  • 13.
    Topics Generics Enhancedfor Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 14.
    Repetitive work ofconverting 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
  • 17.
    Topics Generics Enhancedfor Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 18.
    public static finalint 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(&quot;Red color's wavelength range, &quot; + RED.getStartWavelength()+&quot; ~ &quot;+RED.getEndWavelength()); } } Typesafe enums Example Data members Constructors Methods
  • 21.
    If the implementationof 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
  • 22.
    Topics Generics Enhancedfor Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 23.
    Int add (inta,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
  • 25.
    Topics Generics Enhancedfor Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 26.
    Consider the javaexample: Import java.lang.math.*; double r = Math.cos ( Math.PI * theta ); More readable form: Import static java.lang.math.PI; Import static java.lang.math.cos; double r = cos ( PI * theta ); Static import Example
  • 27.
    Topics Generics Enhancedfor Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 28.
    Annotations are metadatai.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=&quot;val1&quot;, arg2={&quot;arg2.val1&quot;,&quot;arg2.val2&quot;}) public class AnnotationExample { @FieldLevelAnnotation() public String field; @CtorLevelAnnotation() public AnnotationsTest() { // code } @MethodLevelAnnotationA(&quot;val&quot;) @MethodLevelAnnotationB(arg1=&quot;val1&quot;,arg2=&quot;val2&quot;) public void someMethod(String string) { // code } } Metadata (Annotations) Example
  • 30.
    @Retention(retention-policy) – determinesat 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{ Stringstr() 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
  • 32.
    Metadata (Annotations) CategoriesAnnotations Normal annotations Single member annotation Marker annotations
  • 33.
    Normal Annotations — Annotations that take multiple arguments. @MyNormalAnnotation(mem1=&quot;val1&quot;, mem2=&quot;val2&quot;) 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(&quot;a single value&quot;) 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
  • 35.

Editor's Notes

  • #4 Right klick on instance open context menu (access to locks, test jsps, facility to update instance or start kba)
  • #36 Right klick on instance open context menu (access to locks, test jsps, facility to update instance or start kba)