SlideShare a Scribd company logo
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 !!

More Related Content

What's hot (19)

PDF
Javaz. Functional design in Java 8.
Vadim Dubs
 
PPTX
Java New Programming Features
tarun308
 
PPT
Exception Handling1
guest739536
 
PPT
Effective Java - Enum and Annotations
Roshan Deniyage
 
PPT
02basics
Waheed Warraich
 
PPT
Java Generics for Dummies
knutmork
 
PDF
Smart Pointers in C++
Francesco Casalegno
 
PPT
Programming with Java: the Basics
Jussi Pohjolainen
 
PDF
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
 
PDF
Lazy java
Mario Fusco
 
PPT
Java Tut1
guest5c8bd1
 
PPTX
Smart pointers
Vishal Mahajan
 
PPTX
Oop2010 Scala Presentation Stal
Michael Stal
 
PPTX
Qcon2011 functions rockpresentation_scala
Michael Stal
 
PDF
Java Generics - by Example
Ganesh Samarthyam
 
PDF
C++11: Rvalue References, Move Semantics, Perfect Forwarding
Francesco Casalegno
 
PPTX
Oop2011 actor presentation_stal
Michael Stal
 
PPT
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
PPT
Java tut1 Coderdojo Cahersiveen
Graham Royce
 
Javaz. Functional design in Java 8.
Vadim Dubs
 
Java New Programming Features
tarun308
 
Exception Handling1
guest739536
 
Effective Java - Enum and Annotations
Roshan Deniyage
 
02basics
Waheed Warraich
 
Java Generics for Dummies
knutmork
 
Smart Pointers in C++
Francesco Casalegno
 
Programming with Java: the Basics
Jussi Pohjolainen
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
 
Lazy java
Mario Fusco
 
Java Tut1
guest5c8bd1
 
Smart pointers
Vishal Mahajan
 
Oop2010 Scala Presentation Stal
Michael Stal
 
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Java Generics - by Example
Ganesh Samarthyam
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
Francesco Casalegno
 
Oop2011 actor presentation_stal
Michael Stal
 
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
Java tut1 Coderdojo Cahersiveen
Graham Royce
 

Similar to Java 5 Features (20)

PDF
Java 5 New Feature
xcoda
 
PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
Andrew Petryk
 
PPTX
Java fundamentals
HCMUTE
 
PDF
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
Akaks
 
PDF
Wien15 java8
Jaanus Pöial
 
PPT
New features and enhancement
Rakesh Madugula
 
PPT
Core java concepts
Ram132
 
PPT
Operator overloading
Northeastern University
 
PPT
final year project center in Coimbatore
cbeproject centercoimbatore
 
PDF
Java q ref 2018
Christopher Akinlade
 
KEY
About java
Jay Xu
 
PPT
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
PPTX
Chapter 2
application developer
 
PDF
Scala - core features
Łukasz Wójcik
 
PDF
--------------- FloatArrays-java - ckage csi213-lab05-import java-u.pdf
AdrianEBJKingr
 
PPTX
The Art of Java Type Patterns
Simon Ritter
 
PPT
Learning Java 1 – Introduction
caswenson
 
PPT
Java Concepts
AbdulImrankhan7
 
PPT
Unit 4
siddr
 
PPTX
C++11 - STL Additions
GlobalLogic Ukraine
 
Java 5 New Feature
xcoda
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Andrew Petryk
 
Java fundamentals
HCMUTE
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
Akaks
 
Wien15 java8
Jaanus Pöial
 
New features and enhancement
Rakesh Madugula
 
Core java concepts
Ram132
 
Operator overloading
Northeastern University
 
final year project center in Coimbatore
cbeproject centercoimbatore
 
Java q ref 2018
Christopher Akinlade
 
About java
Jay Xu
 
JAVA Tutorial- Do's and Don'ts of Java programming
Keshav Kumar
 
Scala - core features
Łukasz Wójcik
 
--------------- FloatArrays-java - ckage csi213-lab05-import java-u.pdf
AdrianEBJKingr
 
The Art of Java Type Patterns
Simon Ritter
 
Learning Java 1 – Introduction
caswenson
 
Java Concepts
AbdulImrankhan7
 
Unit 4
siddr
 
C++11 - STL Additions
GlobalLogic Ukraine
 
Ad

Java 5 Features

  • 1. Shashank Raj H, 10-Sept-2010 Java 5 features
  • 2. Topics Generics Enhanced for 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 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
  • 9. Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 10. 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
  • 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
  • 13. Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 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
  • 17. Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 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(&quot;Red color's wavelength range, &quot; + RED.getStartWavelength()+&quot; ~ &quot;+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
  • 22. Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 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
  • 25. Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 26. 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
  • 27. Topics Generics Enhanced for Loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)
  • 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=&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) – 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
  • 32. Metadata (Annotations) Categories Annotations 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

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)