MELJUN CORTES Java Lecture Java 5 New Features


Published on

MELJUN CORTES Java Lecture Java 5 New Features

Published in: Technology, News & Politics
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • The actual C++ template mechanism is itself more than just a “clever macro processor,” but the net results are the same: all template evaluation is done at compile time.
  • The actual C++ template mechanism is itself more than just a “clever macro processor,” but the net results are the same: all template evaluation is done at compile time.
  • The interpretation of
    <T extends Comparable<? super T>>
    is “type that extends Comparable and whose supertypes also extend Comparable.” Or, in other words, a type that's comparable to any of its supertypes. Dave Hall has a brief blog entry about this here:
  • My explaination of deserializing causing multiple instances of a class we want to remain singleton was accurate, but I didn't vocalize why we want only one copy: we want to ensure equality tests that use “==” (perfectly reasonable when a singleton is guaranteed, and faster than calling equals()) continue to work, which they won't if there are two of the things extant in a JVM.
  • More correctly, the static import mechanism allows unqualified access to static members. Prior to static imports, one might have coded this by qualifying static members with the class they come from:
    agent.state = RunState.RUNNING;
    or by declaring local constants.
    Note that this is a great anti-example, in that we should use enums instead:
  • Boy, did I get this wrong. A vararg method allows zero or more terms in the variable-length argument, and can have a variable-lenght argument as its sole argument:
    public static int min(int...values) { //...}
    Such a method, then, can be invoked with zero or more terms:
    int minVal = min( );// Legal, if meaningless
    BTW, C# weakly supports varargs, requiring an array of type (although that type can be object[], and since everything is an object....)
    public static int min(params int[] args) { //.... }
  • To answer the question of how varargs is used to implement printf() and format(): all primitive (atomic) parameters are autoboxed into their corresponding reference object wrappers, and those reference objects are passed in as Objects. All I had to do was look up the signature documentation (duh):
    format( String format, Object... args);
    printf( String format, Object... args);
    format( Locale locale, String format, Object... args);
    printf( Locale locale, String format, Object... args);
    format() and printf() probably use reflection to learn the class of each object, as opposed to parsing the format string and presuming therefrom, as must C.
  • David made an interesting comment: he uses annotations in aspect-oriented programming (AOP). That's significant use of annotations directly by programmers, and I take back my comment that annotations were chiefly of interest to tools developers.
    I've not tried AOP yet, but followed this link from CodeHaus's AspectWerkz site (AspectWerks is an AOP framework for Java):
  • MELJUN CORTES Java Lecture Java 5 New Features

    1. 1. New Java 5 Features MELJUN CORTES Java Fundamentals and Object-Oriented Programming The Complete Java Boot Camp MELJUN CORTES
    2. 2. The Big Stuff  Generics  Enumerations  New concurrency constructs  New interfaces  Autoboxing  New loop “for/in”
    3. 3. Less Big Stuff  Static imports  varargs  System.lang.Formatter  Annotations  JVM monitoring and control
    4. 4. Generics  Java Generics were strongly driven by desire for less fiddly Collections programming.  Like C++ templates, provide compile-time resolution of datatype abstractions that preserve type safety and eliminate need for casting.
    5. 5. Generics  Can employ generics in classes, interfaces and methods.  Unlike C++ templates, Generics are more than a clever macro processor: Java compiler keeps track of generics internally, and uses same class file for all instances.
    6. 6. Generic Collections  Six core collections interfaces are synchronization wrappers: Collection abstract generic class  List  Set, SortedSet  Map, SortedMap   Non-generic collections classes (HashMap, etc.) still available, of course.
    7. 7. Simplify Collections Use  Java 1.4 : LinkedList list = new LinkedList(); list.add(new Integer(1)); Integer num = (Integer) list.get(0); ●Java 1.5: LinkedList<Integer> list = new LinkedList<Integer>(); list.add(new Integer(1)); Integer num = list.get(0);
    8. 8. Simplify Collections Use  Original HashMap celebrityCrashers = new HashMap(); celebrityCrashers.put( new Date( “10/05/2005” ), new String( “Lindsay Lohan” ) ); Date key = new Date( "10/1/2005" ); if ( celebrityCrashers.containsKey( key ) ){ System.out.println( "On " + key + “, “ +(String) celebrityCrashers.get( key ) + “crashed a vehicle."); }
    9. 9. Simplify Collections Use  Hot and Crispy Map<Date,String> celebrityCrashers = new HashMap<Date,String>(); celebrityCrashers.put( new Date(“10/05/2005”), new String( “Lindsay Lohan” ) ); Date key = new Date("10/05/2005"); if ( celebrityCrashers.containsKey( key ) ) { System.out.printf( "On %tc, %d crashed a vehicle%n”, key, celebrityCrashers.get( key ) );
    10. 10. Defining Generics  Classes class LinkedList<E> implements List<E> { // implementation } ● Interfaces interface List<E> { void add(E x); Iterator<E> iterator(); } ● Methods void printCollection(Collection<?> c) { for(Object o:c) { System.out.println(o); } }
    11. 11. Wildcards  ? extends Type – a family of Type subtypes  ? super Type – a family of Type supertypes  ? - the set of all Types, or any public static <T extends Comparable<? super T>> void sort(List<T> list) { Object a[] = list.toArray(); Arrays.sort(a); ListIterator<T> i = list.listIterator(); for(int j=0; j<a.length; j++) { i.index(); i.set((T)a[j]); } }
    12. 12. Enumerations  In Java 1.4: 'type safe enum' design pattern: // This class implements Serializable to preserve valid equality // tests using == after deserialization. public final class PowerState implements { private transient final String fName; private static int fNextOrdinal = 1; private final int fOrdinal = fNextOrdinal++; private PowerState(String name) { this.fName = name; } public static final PowerState ON = new PowerState("ON"); public static final PowerState OFF = new PowerState("OFF"); public String toString() { return fName; } private static final PowerState[] fValues = {ON, OFF}; } private Object readResolve () throws{ return fValues[fOrdinal]; }
    13. 13. Enumerations  A bit more concise in Java 5: public enum PowerState {ON, OFF}; ●Enum classes: – declare methods values(), valueOf(String) – implement Comparable, Serializeable – override toString(), equals(), hashCode(), compareTo()
    14. 14. java.util.concurrent  New package that supports concurrent programming  Executor interface executes a Runnable  ThreadPoolExecutor class allows creation of single, fixed and cached thread pools  Executor also executes Callable objects. Unlike Runnable, Callable returns a result and can throw exceptions
    15. 15. Autoboxing  Easier conversion between primative and reference types // Java 1.4 List numbers = new ArrayList(); numbers.add(new Integer(-1)); int i = ((Integer)numbers.get(0)).intValue(); // Java 5 List numbers = new ArrayList(); numbers.add(-1); // Box int to Integer int i = numbers.get(0); // Unbox Integer to int
    16. 16. Static Imports  Langauge support makes it easier to import static members from another class. No more BigBagOf Constants interfaces. import static java.lang.Math.*; ... int x = round(4.5f); ...
    17. 17. Enhanced for Loop Collection<Integer> temperatures = new LinkedHashSet<Integer>(); temperatures.add(105); temperatures.add(92); temperatures.add(7); for(Integer aTemp : temperatures) { System.out.println("This temperature is " + aTemp); }  Hides the loop counter or Iterator....  ...but therefore can't be used when your code needs the counter or Iterator.
    18. 18. Variable Argument List  varargs mechanism allows variable length argument lists. public int min(int first, int... rest) { int min = first; } for(int next: rest){ if (next < min) min = next; } return min;
    19. 19. java.util.Formatter Class  Provides control of string formatting akin to C's printf()  Utilizes a format string and format specifiers  Unlike C format strings, note use of “%” as sole format specifier. No backslashes, such as “n” System.out.printf(“%s crashed on %tc%n”, celebName, crashDate);
    20. 20. Annotations  Let you associate metadata with program elements  Annotation name/value pairs accessible through Reflection API  Greatest utility is to tools, such as code analyzers and IDEs. JDK includes apt tool that provides framework for annotation processing tools.
    21. 21. Annotations  Most useful annotation to programmer: @Override interface Driver { //... int getDrivingSkillsIndex(); } public class Celebrity implements Driver { //... /** * The @Override annotation will let the compiler * catch the misspelled getDrivinSkillsIndex(). */ @Override getDrivinSkillsIndex() { return 0; } //...
    22. 22. Annotations  Next most useful annotations to programmers: @Deprecated, @SuppressWarnings @Deprecated public class BuggyWhip{ ... } //... // @SuppressWarnings selectively turns off javac warnings // raised by use of the -Xlint option @SuppressWarnings({“fallthrough”}) public void iUseSloppySwitchCoding { ... };
    23. 23. Annotations  You can define your own (e.g., to supplant javadoc tags, or annotate for code management practices)  See Chapter 4 of Java In A Nutshell
    24. 24. Monitoring & Management  JMX API ( provides remote monitoring and management of applications  uses JMX to define MXBean interfaces for monitoring and managing a running JVM  MXBean interface lets you monitor class loadings, compilation times, garbage collections, memory, runtime configuration and thread info.  MXBean also provides for granting of JVM monitoring and control permission
    25. 25. Monitoring & Management  java.lang.instrument defines the API to define agents that instrument a JVM by transforming class files to add profiling support, code coverage testing  Instrumentation agent classes define premain() method, which is called during startup before main() for each agent class specified on the Java interpreter command line  Instrumentation object can register ClassFileTransformer objects to rewrite class file byte codes as they're loaded.
    26. 26. References & Credits  Sun J2SE 5 tutorial  Java 5 In A Nutshell (O'Reilly's Nutshell Series)  “A quick tour 'round Java 5”  “Type Safe Enumerations”
    1. A particular slide catching your eye?

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