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

Slides:



Advertisements
Similar presentations
Chapter 4 Loops Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Advertisements

CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
1 Classes and Objects in Java Basics of Classes in Java.
Basic Java Constructs and Data Types – Nuts and Bolts
1 Packages: Putting Classes Together. 2 Introduction The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance)
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Introduction to Computation and Problem
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
10 Copyright © 2005, Oracle. All rights reserved. Reusing Code with Inheritance and Polymorphism.
Introduction to Programming
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Interfaces (Part II) Course Lecture Slides 28 June 2010 A picture is.
Lilian Blot 11 Spring 2014 TPOP 1. Lilian Blot 22 Spring 2014 TPOP 2.
Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
Data Structures ADT List
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
ITEC200 Week04 Lists and the Collection Interface.
Concrete collections in Java library
Double-Linked Lists and Circular Lists
John Hurley Cal State LA
Modern Programming Languages, 2nd ed.
9-Jun-14 Enum s (and a review of switch statements)
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
1 / / / /. 2 (Object) (Object) –, 10 (Class) (Class) –, –, – (Variables) [ Data member Field Attribute](, ) – (Function) [ Member function Method Operation.
Object Oriented Programming with Java
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.
Page 1 – Spring 2010Steffen Vissing Andersen Software Development with UML and Java 2 SDJ I2, Spring 2010 Agenda – week 7, 2010 • Pakages • Looking back.
Review Pseudo Code Basic elements of Pseudo code
The List ADT Textbook Sections
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
COSC 2006 Data Structures I Instructor: S. Xu URL:
1 Arrays An array is a special kind of object that is used to store a collection of data. The data stored in an array must all be of the same type, whether.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Based on slides from Deitel & Associates, Inc.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 9 Interactive Multimedia Authoring with Flash Introduction to Programming 1.
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
1 Unit Testing with JUnit CS 3331 Fall 2009 Kent Beck and Eric Gamma. Test Infected: Programmers Love Writing Tests, Java Report, 3(7):37-50, Available.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 13 – Salary Survey Application: Introducing.
CS18000: Problem Solving and Object-Oriented Programming.
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.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger.
Programming in Scala Chapter 1. Scala: both object-oriented and functional Scala blends –object-oriented and –functional programming in a –statically.
Guide To UNIX Using Linux Third Edition
14-Jul-15 JUnit 4. Comparing JUnit 3 to JUnit 4 All the old assertXXX methods are the same Most things are about equally easy JUnit 4 makes it easier.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
Java 1.5 Annotations. Motivation Computer scientists and engineers are always trying to add new features to programming languages Sometimes they are genuine.
JUnit The framework. Goal of the presentation showing the design and construction of JUnit, a piece of software with proven value.
Effective Java: Generics Last Updated: Spring 2009.
The Java Programming Language
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.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
CompSci 100E 40.1 Java 5 New Features  Generics  Enhanced for loop  Autoboxing/unboxing  Typesafe enums  Other  Varargs  Static Import  Metadata.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
S Ramakrishnan1 Systems V & V, Quality and Standards Dr Sita Ramakrishnan School CSSE Monash University.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Week 6 - Friday.  What did we talk about last time?  Loop examples.
New Java Features Advanced Programming Techniques.
OOP Tirgul 12.
EECE 310: Software Engineering
Java 5 New Features 1-May-19.
Presentation transcript:

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

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

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(); }

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

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

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(); }

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));

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.

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

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 }

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

01/26/07© 2006, uXcomm Inc. Slide 12 Extending Enums public enum Planet { MERCURY (3.303e+23, e6), VENUS (4.869e+24, e6), EARTH (5.976e+24, e6)... 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; } }

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)

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);

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

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); }

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

01/26/07© 2006, uXcomm Inc. Slide 18 JUnit 4 Details Implements 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 running because...") Implements (timeout=5000)

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

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

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(); }