Agenda<br /><ul><li> Generics</li></ul>Compile-time type safety for collections without casting<br /><ul><li> Enhanced for...
Generics - Intro<br />Tutorials : http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf<br /><ul><li>Compile-time type sa...
Methods can be defined to operate on unknown types of Objects without using ‘Objects’ class. And no type casting is required.
Big advantage: collections are now type safe.</li></ul>2<br />Example : ‘Generify ‘ your Java classes –<br />public class ...
Generics – Example 2<br />3<br />Another Example <br />public class GenericFactory<E> {<br />    Class theClass = null;<br...
Generics – Generics in Methods<br />4<br />static <T> void fromArrayToCollection(T[] a, Collection<T> c) {<br />        fo...
Generics – With Collections<br />5<br />Lists<br />List<String> list = new ArrayList<String>(); <br />list.add(“A String”)...
Generics – Diving Deeper<br />6<br />Generics and Subtyping<br />List<String> ls = new ArrayList<String>(); <br />List<Obj...
Generics – Subtyping continued…<br />7<br />Bounded Wildcards<br />List<? extends Shape> is an example of a bounded wildca...
A wildcard with a lower bound looks like " ? super Type " </li></ul>Example :<br />public class Collections { <br />  publ...
Enhanced for-loop or for each loop<br />8<br />New syntax of for loop that works for Collections and Arrays - <br />Collec...
 The for-each construct gets rid of the clutter and the opportunity for error.</li></li></ul><li>Autoboxing<br />9<br />pr...
Enum - Introduction<br />10<br />Java Constants Before JDK 1.5 –<br />public static final int SEASON_WINTER = 0; <br />pub...
Enum - Example<br />11<br />How to define them ..<br />public enum Flavor {<br />    CHOCOLATE(100), //declare all the pos...
Upcoming SlideShare
Loading in …5
×

Java New Programming Features

1,821 views
1,754 views

Published on

Java New Programming Features

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,821
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
47
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Java New Programming Features

  1. 1. Agenda<br /><ul><li> Generics</li></ul>Compile-time type safety for collections without casting<br /><ul><li> Enhanced for loop</li></ul>Automates use of Iterators to avoid errors<br /><ul><li> Autoboxing/unboxing</li></ul>Avoids manual conversion between primitive types (such as int) and wrapper types (such as Integer)<br /><ul><li> Typesafe enums</li></ul>Provides all the well-known benefits of the Typesafe Enum pattern<br />1<br />
  2. 2. Generics - Intro<br />Tutorials : http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf<br /><ul><li>Compile-time type safety without casting.
  3. 3. Methods can be defined to operate on unknown types of Objects without using ‘Objects’ class. And no type casting is required.
  4. 4. Big advantage: collections are now type safe.</li></ul>2<br />Example : ‘Generify ‘ your Java classes –<br />public class Box<T> { <br />private T t ; <br />public void add(Tt ) { <br />this.t = t; <br />} <br />public T get() { <br />return t;<br /> } <br />}<br />How to use this :<br />Box<Integer> integerBox = new Box<Integer>(); <br /> …<br /> integerBox.add(new Integer(25)); //typesafe only Integers can be passed<br /> Integer myInt = integerBox.get() //no typecasting required<br />T is a type parameter that will be replaced by a real type.<br />T is the name of a type parameter.<br />This name is used as a placeholder for the actual type that will be passed to Gen when an object is created.<br />
  5. 5. Generics – Example 2<br />3<br />Another Example <br />public class GenericFactory<E> {<br /> Class theClass = null;<br /> public GenericFactory(Class theClass) {<br /> this.theClass = theClass;<br /> }<br /> public E createInstance() throws …{<br /> return (E) this.theClass.newInstance();<br /> }<br />Usage : Creates a Factory of Generic Type<br />GenericFactory<MyClass> factory = new GenericFactory<MyClass>(MyClass.class);<br />MyClass myClassInstance = factory.createInstance();<br />
  6. 6. Generics – Generics in Methods<br />4<br />static <T> void fromArrayToCollection(T[] a, Collection<T> c) {<br /> for (T o : a) {<br /> c.add(o);<br /> }<br /> }<br /> static <T> Collection<T> fromArrayToCollectionv2(T[] a) {<br /> Collection<T> c = new ArrayList<T>();<br /> for (T o : a) {<br /> c.add(o);<br /> }<br /> return c ;<br /> }<br />One more Interesting Example…<br />public <T> T ifThenElse(boolean b, T first, T second) {<br /> return b ? first : second; <br />}<br />
  7. 7. Generics – With Collections<br />5<br />Lists<br />List<String> list = new ArrayList<String>(); <br />list.add(“A String”); <br />String string2 = list.get(0); // no type casting.<br />Maps (can define multiple typed parameters)<br /> Map<String, String> map = new HashMap<String, String>();map.put ("key1", "value1");map.put ("key2", "value2");String value1 = map.get("key1");<br />Iterating a Generic List:<br />List<String> list = new ArrayList<String>(); <br />Iterator<String> iterator = list.iterator(); <br />while(iterator.hasNext()){ <br />String aString = iterator.next(); <br />}<br />Backward Compatibility<br /> List list = new ArrayList<String>(); <br />Nested Generic Types<br /> List<List<String>> myListOfListsOfStrings;<br />
  8. 8. Generics – Diving Deeper<br />6<br />Generics and Subtyping<br />List<String> ls = new ArrayList<String>(); <br />List<Object> lo = ls; //illegal won’t compile!!<br />What’s the Problem ?<br />lo.add(new Object()); <br />String s = ls.get(0); // attempts to assign an Object to a String!<br />In other words <br />Collection<Object> is not a supertype of all the types of collections<br />To cope with this sort of situation use Wildcards<br />static void printCollection2(Collection<?> c) { // Collection<?> -“collection of unknown”<br /> for (Object e : c) {<br /> System.out.println(e);<br /> }<br /> }<br />Limitation in using unbounded wildcard<br />Any method that takes Generic type of argument cannot be invoked :<br />Collection<?> c = new ArrayList<String>();<br />c.add(new Object()); // compile time error<br />
  9. 9. Generics – Subtyping continued…<br />7<br />Bounded Wildcards<br />List<? extends Shape> is an example of a bounded wildcard.<br /><ul><li>A wildcard with an upper bound looks like " ? extends Type “
  10. 10. A wildcard with a lower bound looks like " ? super Type " </li></ul>Example :<br />public class Collections { <br /> public static <T> void copy <br /> ( List<? super T> dest, List<? extends T> src) { // uses bounded wildcards <br /> for (int i=0; i<src.size(); i++) <br /> dest.set(i,src.get(i)); <br /> } <br />}<br />List<Object> output = new ArrayList< Object >(); List<Long>    input = new ArrayList< Long >(); ... Collections.copy(output,input);  // fine<br />List<String> output = new ArrayList< String >(); List<Long>    input = new ArrayList< Long >(); ... Collections.copy(output,input);  // error <br />
  11. 11. Enhanced for-loop or for each loop<br />8<br />New syntax of for loop that works for Collections and Arrays - <br />Collections :<br />void cancelAll(Collection<TimerTask> c) { <br />for (TimerTask t : c) {<br /> t.cancel();<br /> } <br />}<br />Arrays :<br />int sum(int[] a) { <br /> int result = 0; <br />for (int i : a) {<br /> result += i; <br /> }<br /> return result; <br />}<br />Nested –<br />for (Suit suit : suits) {<br /> for (Rank rank : ranks){ <br /> sortedDeck.add(new Card(suit, rank));<br /> }<br />}<br /><ul><li> No need to use iterators. (The compiler does this for you behind your back)
  12. 12. The for-each construct gets rid of the clutter and the opportunity for error.</li></li></ul><li>Autoboxing<br />9<br />primitive types to be converted into respective wrapper objects and vice versa.<br />(by the Compiler)<br />int i; <br />Integer j; <br />j = 2; // int to Integer automatic conversion<br />i = j; // Integer.intValue() call<br />j = i; // int to Integer automatic conversion<br />Advantages : <br />1. Since Wrapper classes are immutable <br />intObject = new Integer(10); <br />Before Java 5 <br />int intPrimitive = intObject.intValue(); <br />intPrimitive++; <br />intObject = new Integer(intPrimitive); <br />Java 5 AutoBoxing<br />intObject++;<br />2. Easy to use wrapper classes within Collections <br />ArrayList<Integer> list = new ArrayList<Integer>(); <br />for(int i = 0; i < 10; i++)<br /> list.add(i); // Boxing <br />
  13. 13. Enum - Introduction<br />10<br />Java Constants Before JDK 1.5 –<br />public static final int SEASON_WINTER = 0; <br />public static final int SEASON_SPRING = 1; <br />……<br />Issues:<br />Not Type-safe <br /><ul><li> Since season is represented as integer one can pass any integer values, without any compiler warnings.</li></ul>No Name space<br /><ul><li> one may need to refer to java-docs (if any) to check the possible values in case more than one type of constants are declared in a single interface/class. </li></ul>Compile time binding <br />Print Values not self explanatory.<br />JDK 1.5 gets linguistic support for enumerated types as follows :<br />enum Season { WINTER, SPRING, SUMMER, FALL }<br />** Don’t confuse enum with the Enumeration interface, an almost obsolete way of iterating over Collections, replaced by Iterator.<br />
  14. 14. Enum - Example<br />11<br />How to define them ..<br />public enum Flavor {<br /> CHOCOLATE(100), //declare all the possible values first. <br /> VANILLA(120),<br /> STRAWBERRY(80);<br /> private int fCalories; // can have state (member variables)<br /> int getCalories(){ // cusotm method<br /> return fCalories;<br /> }<br /> private Flavor(int aCalories){ // constructor<br /> fCalories = aCalories;<br /> }<br /> }<br />How to use them …<br />String getColor(Flavor flv){ // Used as normal java objects.. <br /> if(flv == Flavor.VANILLA) // “==“ can be used for value comparison<br /> return “White” ;<br /> ……. <br /> switch(flv) { <br /> case VANILLA : // You can use enums as case labels<br /> ……<br />}<br />String color = getColor(Flavor.VANILLA) // no constructor only constant values.<br />
  15. 15. Enum <br />12<br />Facts about enmus :<br /><ul><li>Enums can nave methods, constructors , static and member variables, static block etc..like other java classes.
  16. 16. These can be passed around as Java objects.
  17. 17. Constructors are never invoked outside the Enums (no new operator)
  18. 18. Enums are implicitly final subclasses of java.lang.Enum
  19. 19. equals() and == amount to the same thing.</li></ul>Advantages -<br /><ul><li>You can use enums as case labels.
  20. 20. Methods come built in with enums to do do things like convert enums names to ordinals, and combos with enumset.
  21. 21. You can attach additional fields and code to enum constants.
  22. 22. enums are type safe. With Strings all your items in all categories are the same type. There is nothing to stop you from feeding a fruit category to an animal parameter.
  23. 23. You can compare enums quickly with ==. You don’t need to use equals as you do with String.</li></li></ul><li>Varargs and Static import<br />13<br />Arbitrary number of arguments can be passed using varargs.<br />public static String format(String pattern, Object... arguments){<br /> …..<br />}<br />Here we can pass –<br />format( "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.", 7, new Date(), “abcd");<br />We can also pass an array of objects.<br />Varargs can be used only in the final argument position<br />Static Import<br />import static java.lang.Math.PI;<br />….<br />double r = cos(PI * theta);<br />Advantage :<br />No need to refer same class/package more than one time<br />Disadvantage :<br />Name space is lost. Makes code unmaintainable, Don’t overuse this.<br />
  24. 24. Thanks<br />14<br />

×