Enterprise Java Java SE 5 TM Language Feature Enhancement Primary Source: New Features and Enhancements J2SE 5.0

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Review Generics and the ArrayList Class
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
COMP 121 Week 9: AbstractList and ArrayList. Objectives List common operations and properties of Lists as distinct from Collections Extend the AbstractCollection.
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
New features in JDK 1.5 Can these new and complex features simplify Java development?
Modules Program is built out of components. Each component defines a set of logically related entities (strong internal coupling) A component has a public.
Java Review Interface, Casting, Generics, Iterator.
1-May-15 Java 1.5. Reason for changes “The new language features all have one thing in common: they take some common idiom and provide linguistic support.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Data Structures & Java Generics Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Generics.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
1 Generics, Type Safety, and Dynamic Data Structures.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
1 Java Object Model Part 1. 2 Type Definition: set of values – a set of values and set of operations –a set of operations that can be applied to those.
Creating Generic Classes. Introduction Java Generics were added to allow for type- safe collections and eliminate the need for burdensome, code-cluttering.
Java 1.5 & Effective Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger.
30-Jun-15 Generics. Arrays and collections In Java, array elements must all be of the same type: int[] counts = new int[10]; String[] names = { "Tom",
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
Effective Java: Generics Last Updated: Spring 2009.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
1162 JDK 5.0 Features Christian Kemper Principal Architect Borland.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 11 Arrays Continued
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
24-Oct-15 Java Java beta 1 (“Tiger”) Released February 4, Themes Ease of Development Scalability.
Introduction to Exception Handling and Defensive Programming.
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
CompSci 100E 40.1 Java 5 New Features  Generics  Enhanced for loop  Autoboxing/unboxing  Typesafe enums  Other  Varargs  Static Import  Metadata.
Types in programming languages1 What are types, and why do we need them?
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Objects First With Java A Practical Introduction Using BlueJ Supplementary Material for Java
Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
Georgia Institute of Technology What is new in Java 5.0 (1.5)? Barb Ericson Georgia Institute of Technology June 2006.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
List Interface and Linked List Mrs. Furman March 25, 2010.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CIS 200 Test 01 Review. Built-In Types Properties  Exposed “Variables” or accessible values of an object  Can have access controlled via scope modifiers.
Written by: Dr. JJ Shepherd
Bart van Kuik Application Developer Oracle Corporation.
Iteration Abstraction SWE Software Construction Fall 2009.
The ArrayList Data Structure Standard Arrays at High Speed!
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
New Java Features Advanced Programming Techniques.
Sixth Lecture ArrayList Abstract Class and Interface
Lecture 20: Wrapper Classes and More Loops
Generics 27-Nov-18.
Arrays and Collections
Generics, Lambdas, Reflections
Java 5 New Features 1-May-19.
Generics 2-May-19.
Presentation transcript:

Enterprise Java Java SE 5 TM Language Feature Enhancement Primary Source: New Features and Enhancements J2SE 5.0

Enterprise Java v070123JavaSE 5 Language Enhancements2 Goals Become familiar with Java SE 5 Language Feature Enhancements –required by Java EE 5 –used in class examples

Enterprise Java v070123JavaSE 5 Language Enhancements3 Objectives Generics Enhanced for loop Autoboxing/Unboxing Typesafe Enums Varargs Static Import Metadata (Annotations)

Enterprise Java v070123JavaSE 5 Language Enhancements4 Generics: Raw Types Provide no means to express type to the compiler Require syntactical cast (“hope it works”) –Potential runtime failure (ClassCastException) private static class TestType { public String name; } List rawCollection = new ArrayList(); rawCollection.add(anObject); //the cast to (TestType) is required here TestType rawObject = (TestType)rawCollection.get(0); log.info("raw way=" + rawObject.name);

Enterprise Java v070123JavaSE 5 Language Enhancements5 Generics: Allow code to express type in Collection –“Typed Collection” Compiler can check types during compilation No checks last beyond compile time –allows integration with legacy code List typedCollection = new ArrayList (); typedCollection.add(anObject); //no cast necessary TestType typedObject = typedCollection.get(0); log.info("typed way=" + typedObject.name);

Enterprise Java v070123JavaSE 5 Language Enhancements6 Generics: No Runtime Checks List typedCollection = new ArrayList (); //typed collections get checked at compile time typedCollection.add(anObject); //but things can still happen that bypass compiler List rawCollection = typedCollection; try { rawCollection.add(new String("slipped by 2")); } catch (ClassCastException ex) { fail("unexpected catch of raw Collection"); } Legacy code can still cause errors

Enterprise Java v070123JavaSE 5 Language Enhancements7 Generics: Checked Collections //checked collections verify types at runtime List checkedCollection = Collections.checkedList(typedCollection, TestType.class); rawCollection = checkedCollection; boolean wasCaught = false; try { rawCollection.add(new String("caught")); } catch (ClassCastException ex) { log.info("caught you!"); wasCaught = true; } assertTrue("checked type not caught", wasCaught); Checked Collection wrappers will defend collections at insertion –legacy code will be in stack trace

Enterprise Java v070123JavaSE 5 Language Enhancements8 Enhanced For Loop Iterators –ugly to work with –prone to errors erroneous placement of calls to next() Enhanced For Loops –syntactically simpler –manages iterator not usable when logic requires access to iterator –itr.remove()

Enterprise Java v070123JavaSE 5 Language Enhancements9 For Each Loop: Collections Collection collection = new ArrayList (); collection.add(new String("1")); //... //legacy way int i=0; for(Iterator itr = collection.iterator(); itr.hasNext(); ) { log.info(itr.next()); i++; } assertTrue("unexpected count:" + i, i==collection.size()); //java SE 5 way int i=0; for(String s: collection) { log.info(s); i++; } assertTrue("unexpected count:" + i, i==collection.size());

Enterprise Java v070123JavaSE 5 Language Enhancements10 For Each Loop: Arrays String[] array = new String[3]; array[0] = new String("1"); //... //legacy way int i=0; for(i=0; i<array.length; i++) { log.info(array[i]); } assertTrue("unexpected count:" + i, i==array.length); //java SE 5 way int i=0; for(String s: array) { log.info(s); i++; } assertTrue("unexpected count:" + i, i==array.length);

Enterprise Java v070123JavaSE 5 Language Enhancements11 Autoboxing Java collections prohibit adding primitive types –must wrap in object type collection.add(new Integer(1)); Autoboxing –automatically wraps primitive types in object wrapper when needed Auto-unboxing –automatically extracts the primitive type from the object wrapper when needed

Enterprise Java v070123JavaSE 5 Language Enhancements12 Autoboxing Example private Integer passInteger(Integer i) { log.info("received Integer=" + i); return i; } private Long passLong(Long i) { log.info("received Long=" + i); return i; } //parameter values being manually wrapped //return values being manually wrapped int intWrap = passInteger(new Integer(1)).intValue(); long longWrap = passLong(new Long(1)).longValue(); //parameter values being automatically wrapped (“auto boxing”) //return values being automatically unwrapped (“auto unboxing“) int intBox = passInteger(1); long longBox = passLong(1L);

Enterprise Java v070123JavaSE 5 Language Enhancements13 Autoboxing and Varargs private int sumArray(Integer[] values) { int result = 0; for (int i=0; i<values.length; i++) { result += values[i]; } return result; } private int sumArgs(int...values) { int result = 0; for(int value : values) { result += value; } return result; } int result1 = sumArray(new Integer[] { new Integer(1), new Integer(2), new Integer(3)}); assertTrue("...:" + result1, result1 == 6); int result2 = sumArgs(4, 5, 6); assertTrue("...:" + result2, result2 == 15);

Enterprise Java v070123JavaSE 5 Language Enhancements14 Enums “static final int” Approach –Not typesafe –Not namespaced relies on text prefixes –Brittle values compiled into client classes –No information in printed values Java SE 4 enums –full fledge classes Must be accounted for in O/R Mapping

Enterprise Java v070123JavaSE 5 Language Enhancements15 Enums: names and ordinal values private enum Day { SUN, MON, TUE, WED, THU, FRI, SAT }; public void testEnum() { Day day1 = Day.SUN; Day day2 = Day.WED; log.debug("day1=" + day1.name() + ", ordinal=" + day1.ordinal()); log.debug("day2=" + day2.name() + ", ordinal=" + day2.ordinal()); assertTrue(day1 + " wasn't before " + day2, day1.compareTo(day2) < 0); } (EnumTest.java:testEnum:17) -day1=SUN, ordinal=0 (EnumTest.java:testEnum:18) -day2=WED, ordinal=3

Enterprise Java v070123JavaSE 5 Language Enhancements16 Enums: values private enum Rate { SUN(2), MON(1), TUE(1), WED(1), THU(1), FRI(1), SAT(1.5); double amount; private Rate(double amount) { this.amount = amount; } public double amount() { return amount; } } public void testEnumValues() { int hours = 4; Double wage = 10.0; for (Rate rate : Rate.values()) { Double pay = hours * wage * rate.amount(); log.info("pay for " + rate.name() + "=" + pay); } (EnumTest.java:testEnumValues:36) -pay for SUN=80.0 (EnumTest.java:testEnumValues:36) -pay for MON=40.0 (EnumTest.java:testEnumValues:36) -pay for TUE=40.0 (EnumTest.java:testEnumValues:36) -pay for WED=40.0 (EnumTest.java:testEnumValues:36) -pay for THU=40.0 (EnumTest.java:testEnumValues:36) -pay for FRI=40.0 (EnumTest.java:testEnumValues:36) -pay for SAT=60.0

Enterprise Java v070123JavaSE 5 Language Enhancements17 Enums: behavior private enum Worker { HARD { public String go() { return "CAN DO!"; } }, GOOD { public String go() { return "I'll try"; } }, BAD { public String go() { return "Why?"; } }; public abstract String go(); } public void testEnumBehavior() { for (Worker w : Worker.values()) { log.info(w.name() + " worker says \'" + w.go() + "\' when tasked"); } (EnumTest.java:testEnumBehavior:48) -HARD worker says 'CAN DO!' when tasked (EnumTest.java:testEnumBehavior:48) -GOOD worker says 'I'll try' when tasked (EnumTest.java:testEnumBehavior:48) -BAD worker says 'Why?' when tasked

Enterprise Java v070123JavaSE 5 Language Enhancements18 Static Imports Condition –Frequent use of static methods from another class Solutions –Reference through interface type Test.assertTrue(...) verbose and inconvenient –Implement interface public class MyClass implements MyType, Test {... –void foo() { assertTrue(..) Anti-Pattern –interfaces should define type (MyType), not implementation (Test) –Static imports import static junit.framework.Test; public class MyClass implements MyType {... –void foo() { assertTrue(..)

Enterprise Java v070123JavaSE 5 Language Enhancements19 Annotations Frameworks (e.g., EJB, JAX-WS, JAXB) require significant amounts boiler-plate code –Implementation of these classes is tedious –Can be generated through metadata –Metadata provided through... implementing interface getters() –again, tedious implementing separate descriptors –enough! too tedious annotating javadoc –nice start –information lost after source code processed Java SE 5 Metadata –allows implementation metadata to stay with class –available at runtime

Enterprise Java v070123JavaSE 5 Language Enhancements20 Declaring Annotation Types import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import CallMe { int order(); String alias() default ""; } Alias { String value(); } Each method declares a property Default values make them optional property name 'value' used for Annotated Types with single property

Enterprise Java v070123JavaSE 5 Language Enhancements21 Declaring Annotations with class") public class MyAnnotatedClass { private static final Log log alias="last") public void one() { log.info("one called"); } public void two() { log.info("two public void three() { log.info("three called"); alias="middle") public void four() { log.info("four called"); } }

Enterprise Java v070123JavaSE 5 Language Enhancements22 Using Annotations (at Runtime) private void invoke(Object obj) throws Exception { Class clazz = obj.getClass(); log("class annotations", clazz.getAnnotations()); for(Method m : clazz.getDeclaredMethods()) { log(m.getName() + " annotations", m.getAnnotations()); } -class annotations contained 1 elements class) -one annotations contained 1 elements order=3) -two annotations contained 0 elements -three annotations contained 2 elements order=0) -four annotations contained 1 elements order=1)

Enterprise Java v070123JavaSE 5 Language Enhancements23 Summary Generics –add compiler checks –do not add code (optional Checked Collection classes) Enhanced Iterators –mostly for show - opinion Autoboxing –partially for show - opinion –simplifies component integration Varargs –useful Enums –type-safe, flexible value declarations –new type to map to database Static Imports –eliminates temptation to add implementation to interface Annotations –provides efficient expression of class properties –key addition in language to provide Java EE 5 “simplicity” requirement

Enterprise Java v070123JavaSE 5 Language Enhancements24 References