Presentation is loading. Please wait.

Presentation is loading. Please wait.

01/26/07© 2006, uXcomm Inc. Slide 1 Tuesday Brown Bag with Howard Abrams New Java Features (from Java 5 & 6)

Similar presentations


Presentation on theme: "01/26/07© 2006, uXcomm Inc. Slide 1 Tuesday Brown Bag with Howard Abrams New Java Features (from Java 5 & 6)"— Presentation transcript:

1 01/26/07© 2006, uXcomm Inc. Slide 1 Tuesday Brown Bag with Howard Abrams New Java Features (from Java 5 & 6)

2 01/26/07© 2006, uXcomm Inc. Slide 2 Presentation Contents Generics Enhanced for Loop Autoboxing Enumerations Variable Arguments Annotations Example using Junit Other Java 5 Scripting in Java 6 Other Java 6 Includes SQL DBMS (Apache's Derby) Monitoring Better Performance Updated XML APIs

3 01/26/07© 2006, uXcomm Inc. Slide 3 Generics Containers (collections) now have a type // Removes 4-letter words from c. Elements must be strings static void expurgate (Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) if (((String) i.next()).length() == 4) i.remove(); } // Removes the 4-letter words from c static void expurgate(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) if (i.next().length() == 4) i.remove(); }

4 01/26/07© 2006, uXcomm Inc. Slide 4 Generics Advantages More of a specification is in signature Errors are now caught at compile-time Not at run-time with ClassCastException Flag warnings with the Eclipse IDE Can work for more than just collections Generic type information is present only at compile time May fail when interoperating with ill-behaved legacy code

5 01/26/07© 2006, uXcomm Inc. Slide 5 Caveats to Generics May not use generics if deploy the compiled code on a pre-5.0 VM. Straightforward to use, but not to write Similarity with C++ Templates are superficial Do not generate a new class for each specialization Do not permit template metaprogramming

6 01/26/07© 2006, uXcomm Inc. Slide 6 Enhanced for Loop Iterations are now straight-forward Preserves all of the type safety void cancelAll ( Collection c ) { for (Iterator i = c.iterator(); i.hasNext(); ) i.next().cancel(); } void cancelAll(Collection c) { for (TimerTask t : c) t.cancel(); }

7 01/26/07© 2006, uXcomm Inc. Slide 7 Nested for loops // BROKEN - throws NoSuchElementException! for (Iterator i = suits.iterator(); i.hasNext(); ) for (Iterator j = ranks.iterator(); j.hasNext(); ) sortedDeck.add(new Card(i.next(), j.next())); for (Iterator i = suits.iterator(); i.hasNext(); ) { Suit suit = (Suit) i.next(); for (Iterator j = ranks.iterator(); j.hasNext(); ) sortedDeck.add(new Card(suit, j.next())); } for (Suit suit : suits) for (Rank rank : ranks) sortedDeck.add(new Card(suit, rank));

8 01/26/07© 2006, uXcomm Inc. Slide 8 Works for Arrays too // Returns the sum of the elements of a int sum (int[] a) { int result = 0; for (int i : a) result += i; return result; } Deals with end of the array automatically Note: Can't use it everywhere, for you may need the index value or access to iterator.

9 01/26/07© 2006, uXcomm Inc. Slide 9 Autoboxing Treat an Integer like an int Helpful on collections (can't store primitives) public int fiveMore (Integer v) { return v + 5; } public Integer fiveMore (int v) { return v + 5; } Note: If you autounbox a null, it will throw a NullPointerException

10 01/26/07© 2006, uXcomm Inc. Slide 10 Enumerations final static int has problems: Not typesafe: setColor ( WINTER ); No namespace: SEASON_WINTER Brittleness. Must recompile clients if changed Printed values are uninformative Could create a new Enum class. Ugh! Now enums look like C, C++ and C# enum Season { WINTER, SPRING, SUMMER, FALL }

11 01/26/07© 2006, uXcomm Inc. Slide 11 Enumeration Features The enum declaration defines a class Not integers... keeps original name Work with generics and new for syntax Provides implementations of Object methods They are Comparable and Serializable The class made by enum is immutable Add arbitrary methods and fields to an enum type, and to implement arbitrary interfaces

12 01/26/07© 2006, uXcomm Inc. Slide 12 Extending Enums public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6)... private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } public double mass() { return mass; } public double radius() { return radius; } }

13 01/26/07© 2006, uXcomm Inc. Slide 13 Create a set containing either a range: Or specific members: This is very efficient (backed by bitmap) EnumSet and EnumMap enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY... } for ( Day d : EnumSet.range(Day.MONDAY, Day.FRIDAY) ) System.out.println(d); EnumSet.of(Style.BOLD, Style.ITALIC)

14 01/26/07© 2006, uXcomm Inc. Slide 14 Variable Arguments Methods can be defined like a C function: String format(String pat, Object... args); Must be the last argument (obviously) Call method with comma-separated items: format("On {0,date}: {1}", date, msg); Can pass in an array instead Now have a C-style printf: System.out.printf( "passed=%d; failed=%d%n", passed, failed);

15 01/26/07© 2006, uXcomm Inc. Slide 15 Annotations Markers in your source code for tools Don't do anything explicitly Stored in both the source and class files Replaces ad hoc methods Built using features like Reflection Side-files that need to be maintained Easy to make your own annotations

16 01/26/07© 2006, uXcomm Inc. Slide 16 JUnit 3 Example public class CalculatorTest extends TestCase { public void setup() {... } public void teardown() {... } public void testDivisionByZero() { boolean testPassed = false; try { new Calculator().divide( 4, 0 ); } catch (ArithmeticException e) { testPassed = true; } assertTrue(testPassed); }

17 01/26/07© 2006, uXcomm Inc. Slide 17 JUnit 4 Example public class CalculatorTest { @Before public void prepareTestData() {... } @After public void cleanupTestData() {... } @Test (expected=ArithmeticException.class) public void divisionByZero() { new Calculator().divide( 4, 0 ); }

18 01/26/07© 2006, uXcomm Inc. Slide 18 JUnit 4 Details Implements a @beforeclass and @afterclass that is only run once per class, not for each and every test Create parameterized tests that execute the same tests with different data Implements a @Ignore("Not running because...") Implements a @Test (timeout=5000)

19 01/26/07© 2006, uXcomm Inc. Slide 19 Other Java 5 Features Formatted input and ouput: System.out.printf() Importing static methods import static java.awt.BorderLayout.*; Concurrency Utility library provides Executors (thread task framework) Thread safe queues Timers Locks (including atomic ones) Semaphores

20 01/26/07© 2006, uXcomm Inc. Slide 20 Scripting Support Allows any Java application to execute scripts from a variety of languages The scripts have access to Java objects The scripts can return data back to Java Caveat: The scripting language must be written for the JVM (implemented in Java) Ruby scripts... JRuby Python scripts... Jython Comes with Javascript by default

21 01/26/07© 2006, uXcomm Inc. Slide 21 Scripting Example ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine rubyEngine = m.getEngineByName("jruby"); Bindings bindings = rubyEngine.createBindings (); bindings.put ("y", new Integer(4)); String script = "x = 3 \n" + "2 + x + $y"; try { Object results = rubyEngine.eval(script, bindings); System.out.println (results); } catch (ScriptException e) { e.printStackTrace(); }


Download ppt "01/26/07© 2006, uXcomm Inc. Slide 1 Tuesday Brown Bag with Howard Abrams New Java Features (from Java 5 & 6)"

Similar presentations


Ads by Google