java 7 new features
TRANSCRIPT
Java 7 New Features
Jussi Pohjolainen
Java SE 7 Cer8fica8on
• “Raising the Bar”: more advanced skills needed to pass
• All new defini8on and focus: – The Associate level has gone through significant changes, and the Professional level is both broader and deeper
• New cer8fica8ons – Oracle Cer8fied Associate, Java SE 7 Programmer – Oracle Cer8fied Professional, Java SE 7 Programmer
Oracle Certified Associate, Java SE 7 Programmer (OCA)
• No prequisi6es • Dura8on 140 min, number of ques8ons 90, passing score 77%
• Price 200 – 300 e
OCA: Exam Topics
• Java Basics • Working with Java types • Using opera8ons and Decision Constructs • Crea8ng and Using Arrays • Using Loop Constructs • Working with Methods and Encapsula8on • Working with Inheritance • Handling Excep8ons
Oracle Certified Professional, Java SE 7 Programmer (OCP)
• You have to pass OCA first! • Dura8on 150 min, number of ques8ons 90, passing score 65 %
• Price 200 – 300 e
OCP: Exam Topics
• Java Class Design • Advanced Class Design • OO Principles • Generics and Collec8on • String processing • Excep8ons and Asser8ons
• Java I/O Fundamentals
• Java File I/O (NIO.2) • Building Database Applica8ons with JDBC
• Threads • Concurrency • Localiza8on
Upgrade your Cer8fica8on
• Prior cer6fica6on – Any version of Oracle Cer8fied Professional, Java Programmer OR any version of Sun Cer8fied Java Programmer
• 1Z0-‐805 Upgrade to Java SE 7 Programmer • Dur 150 min, Number of ques8ons: 90, passing score: 60%
• Price 200 e – 300 e
Upgrade Exam Topics • Language Enhancements
– Project Coin • Design pa@erns
– Singleton, composi8on, DAO, factory
• Database Applica6ons with JDBC – JDBC API: RowSetProvider,
RowSetFactory, new RowSet interfaces
• Concurrency – Atomic variables, locks,
executors, fork/join • Localiza6on
– Locales, resource bundles • Java File I/O (NIO.2)
– Path and Files -‐ classes
(RECAP) JAVA 5 AND 6
Versions and Naming
JDK/Year
JDK 1.1 (1997) New Event Model, Inner classes, JavaBeans and JDBC
J2SE 1.2 (1998) Collec8on Framework, Reflec8on, Swing API
J2SE 1.3 (2000) HotSpot JVM, JavaSound, JNDI
J2SE 1.4 (2002) Regex, excep8on chaining, XML Parser, XSLT, Java Web Start
J2SE 5.0 or 1.5 (2004) For-‐each, generics, autoboxing, var-‐args
Java SE 6 (2006) Scrip8ng support, annota8ons, GUI enhancements
Java SE 7 (2011) …
New Features • Java SE 5
– Generics – Autoboxing – Improved looping syntax – Annota8ons – …
• Java SE 6 – XML Processing and Web Services – Scrip8ng – JDBC 4.0 – …
Generics ArrayList list = new ArrayList();
list.add("a");
list.add("b");
list.add(new Integer(22));
Iterator i = list.iterator();
while(i.hasNext()) {
System.out.println((String) i.next());
}
Result
Using Generics ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add(new Integer(22));
Iterator<String> i = list.iterator();
while(i.hasNext()) {
System.out.println((String) i.next());
}
Result
Enhanced for -‐ loop ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
// Loop array or collection. Iteration used
// even without declaration! The list object
// must implement java.lang.Iterable interface
for(String alphabet : list) {
System.out.println(alphabet);
}
Java 1.4 import java.util.*; class Main { public static void main(String [] args) { // Does not work, 5 is not a Object type! someMethod(5); } public static void someMethod(Object a) { System.out.println(a.toString()); } }
Java 1.4: Solu8on import java.util.*; class Main { public static void main(String [] args) { Integer temp = new Integer(5); someMethod(temp); } public static void someMethod(Object a) { System.out.println(a.toString()); } }
Java 1.4: Lot of Coding
Integer a = new Integer(5);
Integer b = new Integer(6);
int aPrimitive = a.intValue();
Int bPrimitive = b.intValue();
Autoboxing Comes to Rescue!
class Main {
public static void main(String [] args) {
// Boxing
Integer a = 2;
// UnBoxing
int s = 5 + a;
}
}
Java 1.5 class Main { public static void main(String [] args) { // Works! someMethod(5); } public static void someMethod(Object a) { System.out.println(a.toString()); } }
Java 1.5: For-‐each import java.util.*; class Main { public static void main(String [] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(new Integer(6)); list.add(7); for(int number : list) { System.out.println(number); } } }
for-‐each
Enum • An enum type is a type whose fields consist of a fixed set of
constants • Before (not type-‐safe, no meaningful prin8ng) public static final int WHITE = 0; public static final int BLACK = 1; … • Now: enum Color { WHITE, BLACK, RED, YELLOW, BLUE; }
Usage enum Color { WHITE, BLACK, RED, YELLOW, BLUE; } class Main { public static void main(String [] args) { System.out.println(Color.WHITE); Color c1 = Color.RED; System.out.println(c1); }
Enum: Far more than in other languages
• Enum declara8on defines a full fledged class! • Enum constants are public final sta6c • Compiler adds special methods like values that returns an array containing all the values of the enum.
• Enum class extends java.lang.enum
Enum enum Color { WHITE, BLACK, RED, YELLOW, BLUE; } class Main { public static void main(String [] args) { for (Color c : Color.values()) { System.out.println(c); } } }
Enum Fun enum Color { WHITE, BLACK, RED, YELLOW, BLUE; @Override public String toString() { //only capitalize the first letter String s = super.toString(); return s.substring(0, 1) + s.substring(1).toLowerCase(); } } class App { public static void main(String [] args) { System.out.println(Color.WHITE); } }
Enum Fun enum Color { WHITE(2), BLACK(23), RED(123), YELLOW(124), BLUE(225); private int code; private Color(int c) { code = c; } public int getValue() { return code; } } class App { public static void main(String [] args) { System.out.println(Color.WHITE.getValue()); } }
Sta8c Import (1/2)
class Main {
public static void main(String [] args) {
int x = Integer.parseInt("55");
int y = Integer.parseInt("56");
int x = Integer.parseInt("57");
}
}
Sta8c Import (2/2)
import static java.lang.Integer.parseInt; class Main { public static void main(String [] args) { int x = parseInt("55"); int y = parseInt("56"); int z = parseInt("57"); } }
Metadata: annota8ons
• With Java 5 it’s possible to add metadata to methods, parameters, fields, variables..
• Metadata is given by using annota6ons • Many annota3ons replace what would otherwise have been comments in code.
• Java 5 has built-‐in annota8ons
Uses
• Informa8on to compiler – Detect errors or suppress warnings
• Compiler-‐8me and deployment-‐8me processing – Somware tools may generate code, XML – files..
• Typical applica8on programmers will never have to define an annota8on type, but it is not hard to do so.
Example
@Override
public void method() {
…
}
Example
@Author(
name = ”Jussi Pohjolainen",
)
class MyClass() {
…
}
Example
@Author(”Jussi Pohjolainen”)
class MyClass() {
…
}
Example
@Author(
name = ”Jussi Pohjolainen",
date = ”2012-09-12"
)
class MyClass() {
…
}
Crea8ng Annota8on // Annotation type @interface ClassDocumentation { String author(); String date(); int currentRevision() default 1; } @ClassDocumentation( author = "Jussi Pohjolainen", date = "2012-09-12", currentRevision = 2 ) class Foo { }
Javadoc
Crea8ng Annota8on import java.lang.annotation.*; @Documented @interface ClassDocumentation { String author(); String date(); int currentRevision() default 1; } @ClassDocumentation( author = "Jussi Pohjolainen", date = "2012-09-12", currentRevision = 2 ) class Foo { }
Javadoc now
Targets // Annotation type import java.lang.annotation.*; @Target(ElementType.METHOD) @interface Something { String foo(); } class Foo { @Something(foo = "hello") public void method() { } }
Override: Does not Compile! class Human { public void eat() { System.out.println("Eats food"); } } class Programmer extends Human { @Override public void eatSomeTypo() { System.out.println("Eats pizza"); } } class Main { public static void main(String [] args) { Programmer jack = new Programmer(); jack.eat(); } }
Other Annota8ons used By Compiler
• @Depricated – Gives warning if when depricated method or class is used
• @SuppressWarnings – Suppress all warnings that would normally generate
System.out.format import java.util.Date;
class Main {
public static void main(String [] args) {
Date d = new Date();
// Lot of format characters available!
System.out.format("Today is %TF", d);
}
}
Variable Argument List class Main { public static void printGreeting(String... names) { for (String n : names) { System.out.println("Hello " + n + ". "); } } public static void main(String[] args) { String [] names = {"Jack", "Paul"}; printGreeting("Jack", "Paul"); printGreeting(names); } }
User Input: Scanner
Scanner in = new Scanner(System.in);
int a = in.nextInt();
String b = in.nextLine();
Java 6: XML & Web Services
• Easy way of crea8ng Web Services • Expose web service with a simple annota8on
Web Service package hello; import javax.jws.WebService; @WebService public class CircleFunctions { public double getArea(double r) {
return java.lang.Math.PI * (r * r); } public double getCircumference(double r) { return 2 * java.lang.Math.PI * r; } }
Server package hello;
import javax.xml.ws.Endpoint; class Publish {
public static void main(String[] args) {
Endpoint.publish( "http://localhost:8080/circlefunctions", new CircleFunctions());
}
}
Generate Stub Files
• Generate stub files: – wsgen –cp . hello.CircleFunctions
Java 6: Rhino
• Framework to connect to Java programs to scrip6ng-‐language interpreters.
• Rhino JS Engine comes with Java 6 • To ability to run JS from Java and JS from command line
• Rhino is wrioen in Java
Example import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Main { public static void main(String[] args) { ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("JavaScript"); // Now we have a script engine instance that // can execute some JavaScript try { engine.eval("print('Hello')"); } catch (ScriptException ex) { ex.printStackTrace(); } } }
Java 6: GUI
• Faster Splash Screens – SplashScreen class – java -splash:java-logo.jpeg Main
• System tray support • Wri8ng of Gif -‐ files
Java 6: DB Support
• Java 6 comes with preinstalled rela8onal database, Oracle release of Apache Derby Project
• Java DB is installed automa8cally as part of the Java SE Development Kit (JDK).
• For a Java DB installa8on, set the DERBY_HOME environment variable and classpaths
• Two modes: Embedded and Server
Derby loca8on
Derby Path Serngs
Derby System Info
Crea8ng Database
ij
• The ij is an interac8ve scrip8ng tool • Queries against a Derby database • Can be started with “ij” if in path
EXERCISE 1
JAVA 7 NEW FEATURES
Overview
• Java 7 is an evolu6onary update • In overall
– 1) Small language changes (Project Coin) – 2) Updates to File API – 3) Updates to virtual machine, invokedynamic – 4) Lot of smaller updates
Java 7: Feature changes • Virtual Machine
– JSR 292: JVM support for dynamic languages • Language changes
– JSR 334: Small language changes (Project Coin) • IO
– JSR 203: New file I/O library • I18n
– Unicode 6.0, separate user locale and user-‐interface locale • Client
– Java 2D and Swing updates • JDBC
– JDBC 4.1 (autoclosable) • Web
– Update XML stack to latest version
Java Specifica8on Request (JSR)
• JSR is a formal document that describes specifica8ons and technologies for Java plavorm
• List of JSRs – http://en.wikipedia.org/wiki/Java_Community_Process#List_of_JSRs
• You can see each JSR from jcp.org – http://jcp.org/en/jsr/detail?id=334 (project coin)
Tools
• Download Java SE 7 from Oracle – http://www.oracle.com/technetwork/java/javase/downloads/index.html
• Full support from Netbeans 7 and Eclipse 3.7.1 • If you need to compile to older versions, use
– javac –source 6 –target 6 MyApp.java
PROJECT COIN (JSR 334)
Project Coin
• Adds small language changes to Java SE 7 • Changes are
1. Strings in switch 2. Binary integral literals and underscores in
numeric literals 3. Mul8-‐catch 4. Improved Type Inference for Generic Instance
Crea8on 5. try-‐with-‐resources statement
1. Strings in switch
• Now you can use Strings in switch statement • No duplicate labels • No null labels
Example
2. Binary integral literals and underscores in numeric literals
• Improve readibility – int billion = 1_000_000_000;
• Binary literals, add prefix 0b to number – int one = 0b0000_0001;
Example
3. Mul8-‐catch
• Defining mul8ple excep8ons in one catch block
• Use | (or) as separator between excep8on types
• Simplify excep6on handling
Example
4. Type Inference
• For collec8ons, no need to repeat the generic typing (diamond)
– Map<String, String> coll = new HashMap<>();
5. try-‐with-‐resources statement
• When you open a stream, you must close it • If done correctly, closing of the stream may require lot of coding…
Java 7 to the rescue!
How?
• Virtual Machine will call automa6cally the close method upon exi8ng the try block (like finally)
• The resource object must implement AutoCloseable interface
• The interface has only one method: close • If closing causes excep8on, it’s suppressed (ignore). Possible to get it using getSuppressed() method
Java 7 API
Exercise 2
FILE SYSTEM
API Updates to File System
• java.io and java.nio are updated • Called NIO.2 revision • New classes (java.nio):
– Path – Locate a file in a file system • Paths – Convert a URI to Path object
– Files – Operate on files, directories and other types of files
– FileVisitor – Traversing files in a tree – WatchService – File change modifica8on API
java.nio.file.Path
• Absolute or rela8ve path, refers to files in file system. • Suppor+ng API to java.io.File • File to Path:
– File f = new File(”/foo/bar/file.txt”); – Path p = f.toPath();
• Path to File – File f2 = p.toFile();
• Path is an interface! Instan8a8ng using either File or or Paths class – Path p = Paths.get(“file.txt”);
Nio2: Features
• Able to access informa8on about the path • Support for directory watching • Improved support for large directories
– No hanging or out of memories when dealing with massive directory trees
Demo: Path -‐ class
java.nio.file.Files
• Features – Copy – Create directories – Create files – Create links – Use of the “temp” – folder – Delete – Aoributes – Modified/Owner/Permission – Read / Write
java.nio.file.Files
• Sta8c methods for reading, wri8ng and manipula8ng files and directories
• Files uses Path objects! • Methods like
– createFile(Path p, ..); – delete(Path p); – move(…) – write(Path p, byte [] b, ..) – readAllLines(Path p, Charset cs)
Example
Example
java.nio.file.FileVisitor
• Recursively visit files in a file tree – Example: delete every .class file in a tree
• Implement a class that implements FileVisitor interface – preVisitDirectory – postVisitDirectory – visitFile – visitFileFailed
• Or extend SimpleFileVisitor that has default behaviour for each of these methods!
Idea
• File tree traversal completes when all accessible files in tree has been visited or a visit returns TERMINATE
• Symbolic links are not followed by this method by default
• You can set the depth: 0 (only star8ng file) to MAX_VALUE (all levels)
Traversing the Tree
FileVisitor
java.nio.file.WatchService
• Monitor directory for changes • Example: text editor no8fies if someone else has made changes to your document – (“The following files were changes by another program”)
• Watch Service API enables you to register a directory with the watch service
• When registering tell are you interested in file crea8on, file dele8on or file modifica8on!
Steps
• Create WatchService “watcher” for the file system • Register a directory with the watcher. Specify also types you are interested in: modify, delete…
• Implement infinite loop for wai8ng of incoming events. When event occurs, a key is signaled and put tuo queue
• Retrieve the key, obtain file name from the key • Retrieve a event from the key and process as needed • Reset the key and resume wai8ng for events • Close the service
Registering
Polling
Exercise 3
SWING ENHANCEMENTS
Swing Enhancements
• JLayer • Nimbus Look & Feel • Shaped and Translucent Windows
JLayer
• JLayer enables you to draw on components and respond to component events without modifying the underlying component directly
• So you add a layer on top another component
Nimbus
About Nimbus
• Moved to standard API namespace: javax.swing
• Cross-‐plavorm look and feel • Uses 2D Vector Graphics • Highly Customizable
Serng Theme
• When star8ng – UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
• Amer start –
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
– SwingUtilities.updateComponentTreeUI(this);
Component Sizes
Changing Color Theme
Replace Default Color • UIManager.put("nimbusBase", new Color(...)); • UIManager.put("nimbusBlueGrey", new Color(...)); • UIManager.put("control", new Color(...));
Translucent Window
GUIs in the future.. Java Swing?
Java FX
• JavaFX is the next step in the evolu8on of Java as rich client plavorm
• XML-‐based markup language for defining user interfaces.
• Mul8-‐touch support! • Visual UI Design tool • Is JavaFX replacing Swing? Yes. However, it takes 6me…
Exercise 4
INVOKEDYNAMIC (JSR 292)
Word about JVM when you write in Java: Object x; ... x.equals("hello"); this is compiled into something like: aload_1 ; push local variable 1 (i.e. 'x') onto stack ldc "hello" ; push the string "hello" onto stack ; invoke the equals method invokevirtual java/lang/Object/equals(Ljava/lang/Object;)Z ; the boolean result is now on the stack
Method Invica8on in JVM
• invokevirtual – dispatches a Java Method • invokespecial – instance ini3aliza3on (constructor)
• invokeinterface – dispatches a method declared inside interface
• invokestatic – calls a sta3c method • invokedynamic (new!)
InvokeDynamic
• Possible to call methods that were not known compile 8me!
• You can use API to use bytecode command invokedynamic
Example
Determing the Method in run8me
What is the use?
• For normal coding, rare uses • Some u8li8es (reflec8on) • For future: Virtual machine supports different languages! Scrip8ng languages
Exercise 5
CONCURRENCY UPDATES: FORK/JOIN
Fork / Join
• API for parallel, divide and conquer algorithm • Large task, split into two. If the two tasks are large enough, split these again… con8nue this un8l tasks are acceptable size
• When task is completed, it’s joined with the other task.. this will con8nue un8l one task is returned
Fork/Join • Fork/Join framework helps take advantage of mul6ple processors when crea8ng threading
• Designed for work that can be broken into smaller pieces recursively
• Meant for dividing work to subparts, executes in parallel, then joining them again.
• Idea: – Worker threads in thread pool (ForkJoinPool -‐ class) – When worker thread run out of of things to do, the worker thread can steal tasks from other threads that are s8ll busy (ForkJoinTask – class)
Example
• Increment array values by one. • One solu8on
– Create loop from 0 – array.length and increment each value. Not effec6ve for large arrays!
• Another solu8on – If array is large, split the array into two (or more) and increment these in parallel
– Processing is done in separate CPUs when using Fork/Join!
Basic Use: ForkJoinTask if (my portion of the work is small enough) {
do the work directly
}
else {
split my work into independent pieces
invoke the the pieces (fork)
wait for the results (join)
compose result
}
Classes
• ForkJoinTasks runs in ForkJoinPool • Two concrete tasks (subclasses of ForkJoinTask):
• RecursiveTask – Compute method returns some value.
• RecursiveAction • Compute method doesn’t return a value.
• ForkJoinPool – Manage and monitor the tasks.
Example
• We want to calculate the sum of array – {1,2,3,4,5} => 15
• This can be done using fork/join. • Divide the array to pieces and calculate the sum in different tasks.
{10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30}
{10,11,12,13,14,15,16,17,18,19,20} {21,22,23,24,25,26,27,28,29,30}
{10,11,12,13,14,15} {16,17,18,19,20} {21,22,23,24,25} {26,27,28,29,30}
75 + 90 + 115 + 140
420
Start the Calcula8on
Structure of the SumTask class SumTask extends RecursiveTask<Long> { private static final int THRESHOLD = 5000; private int [] array; private int start; private int end; public SumTask(int [] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public Long compute() {...} }
compute()
Exercise 6
VIRTUAL MACHINE UPDATES
Virtual Machine Updates
• invokedynamic • New garbage collector algorithm: G1
Garbage Collector
• Garbage collector works to reclaim areas of memory within an applica8on that will never be accessed again
• Two steps – Which objects are no longer referenced? – Reclaim memory of dead objects
GC Algorithms
• Java SE main algorithms – Serial collector – Parallel collector – Concurrent-‐mark-‐sweep collector (CMS)
• And now a new! – G1 collector
• Plan is that G1 will replace CMS
Different algorithms
• Serial collector – Uses single thread to perform garbage collec8on. Best-‐suited for singleprocessor machines. On by default.
• Parallel collector – Is Parallel but not concurrent. Pauses threads to do the work!
– For apps with medium-‐ or large-‐sized data sets that run on mul8processor environments.
Different algorithms • CMS
– Is parallel and par8ally concurrent. Pauses some threads to do its work.
– It is designed for applica8ons with medium-‐ to large-‐sized data sets for which response 6me is more important than overall throughput, since the techniques used to minimize pauses can reduce applica8on performance
• G1 – Is parallel and mostly concurrent. Pauses some threads, but only during certain phases of collec8on.
– Targeted for mul8-‐processor server side apps with large memories and response 8me is important. You can set pause-‐6mes.
Serng the Algorithm
java -XX:+UseSerialGC MyApp
java -XX:+UseParallelGC MyApp
java -XX:+UseConcMarkSweepGC MyApp
java -XX:+UseG1GC MyApp
JDBC 4.1
JDBC 4.1
1. AutoClosable: Connec8on, ResultSet, Statement
2. RowSet 1.1: RowSetFactory – easy crea8on of JdbcRowSet
Automa8cally Close Resources
• Automa8cally close: – java.sql.Connection – java.sql.Statement – java.sql.ResultSet
import java.io.*;
import java.net.*;
import java.sql.*;
class MyJDBC {
public static void main(String [] args) {
String driver = "jstels.jdbc.csv.CsvDriver2";
String url = "jdbc:jstels:csv:./csvfiles";
try {
// Load and register the driver
Class.forName(driver);
} catch(ClassNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
try(Connection conn = DriverManager.getConnection(url)) {
// Create a connection to the database
String sql = "SELECT * FROM products";
try (Statement stmt = conn.createStatement()) {
// ResultSet is automatically closed, when Statement is closed.
ResultSet rs = stmt.executeQuery(sql);
String prodid, desc;
// Iterate over the ResultSet using next()
while(rs.next()){
// Use the appropriate getter functions to access columns
prodid = rs.getString("PRODID");
desc = rs.getString("DESCRIPTION");
System.out.println(prodid + " " + desc);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
}
}
Enhanced ResultSet
• A JdbcRowSet object is an enhanced ResultSet object.
• Main uses of a JdbcRowSet object is to make a ResultSet object scrollable and updatable when it does not otherwise have those capabili8es
• You can add listeners: – addRowSetListener
• cursorMoved • rowChanged • rowSetChanged
Java 7: RowSet 1.1
• RowSetFactory – easy crea8on of RowSet Object
• Different Row sets – FilteredRowSet
• Filters number of rows visible in RowSet object, work only with data that is relevant
– CachedRowSet • Operates without being connected to database
RowSetFactory myRowSetFactory = null;
try {
// Java 7: Create instance of JdbcRowSet using RowSetFactory
myRowSetFactory = RowSetProvider.newFactory();
// Closing the JdbcRowSet
try (JdbcRowSet jdbcRs = myRowSetFactory.createJdbcRowSet()) {
jdbcRs.setUrl(url);
jdbcRs.setCommand("select * from products");
jdbcRs.execute();
jdbcRs.next();
System.out.println(jdbcRs.getString(1));
System.out.println(jdbcRs.getString(2));
jdbcRs.next();
System.out.println(jdbcRs.getString(1));
System.out.println(jdbcRs.getString(2));
jdbcRs.previous();
System.out.println(jdbcRs.getString(1));
System.out.println(jdbcRs.getString(2));
}
} catch(SQLException e) {
e.printStackTrace();
}
JAVA 8
Some of Proposed content
• Project Jigsaw • Project Lambda • JavaFX 3.0 • Device Support
– Mul8-‐touch, Camera, Loca8on, Compass, Accelerometer
Jigsaw • Group of classes and resources and a special module-‐info file that declares dependencies
• Module is a collec8on of classes with a name, version number and formal descrip8on of it’s rela8onship with other modules.
• Most important rela8onship: dependence (requires)
module com.greetings @ 0.1 { requires org.astro @ 1.2; // requires a specific version class com.greetings.Hello; }
Lambda
• Perhaps the most important language change: Lambda expressions
Mo8va8on class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
//do something
}
}
class UIBuilder {
public UIBuilder() {
button.addActionListener(new ButtonHandler());
}
}
Mo8va8on class UIBuilder {
public UIBuilder() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do something
}
}
}
}
We must create instance to just call one
method!
Lambda Expression! class UIBuilder {
public UIBuilder() {
button.addActionListener(ActionEvent e -> // do something )
}
}
Lambda Expressions
• Lambda expressions are 8ny anonymous methods
• The syntax – (type parameter) -‐> func8on_body
• Example – (String s1, String s2) -‐> s1.length() – s2.length()
Lambda Expressions
• Lambda expressions are 8ny anonymous methods • The syntax
– (type parameter) -> function_body • Example
– (String s1, String s2) -> s1.length() – s2.length()
• Example – List <String> list = Arrays.asList("looooong", "short", "tiny" );
– Collections.sort(list, (String s1, String s2) -> s1.length() - s2.length());
Thank you!