SlideShare ist ein Scribd-Unternehmen logo
1 von 166
Downloaden Sie, um offline zu lesen
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	
          •  Java	
  File	
  I/O	
  (NIO.2)	
  
•    Advanced	
  Class	
  Design	
      •  Building	
  Database	
  
•    OO	
  Principles	
                    Applica8ons	
  with	
  JDBC	
  
•    Generics	
  and	
  Collec8on	
     •  Threads	
  
•    String	
  processing	
             •  Concurrency	
  
•    Excep8ons	
  and	
                 •  Localiza8on	
  
     Asser8ons	
  
•  Java	
  I/O	
  Fundamentals	
  
	
  
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	
                    •  Concurrency	
  
    –  Project	
  Coin	
                             –  Atomic	
  variables,	
  locks,	
  
•  Design	
  pa@erns	
                                  executors,	
  fork/join	
  
    –  Singleton,	
  composi8on,	
  DAO,	
       •  Localiza6on	
  
       factory	
                                     –  Locales,	
  resource	
  bundles	
  
•  Database	
  Applica6ons	
  with	
  JDBC	
     •  Java	
  File	
  I/O	
  (NIO.2)	
  
    –  JDBC	
  API:	
  RowSetProvider,	
             –  Path	
  and	
  Files	
  -­‐	
  classes	
  
       RowSetFactory,	
  new	
  RowSet	
  
       interfaces	
  
(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.nimb
         us.NimbusLookAndFeel");
•  Amer	
  start	
  
    – 
       UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusL
       ookAndFeel");
    –  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!	
  

Weitere ähnliche Inhalte

Was ist angesagt?

Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIGanesh Samarthyam
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습DoHyun Jung
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/HibernateSunghyouk Bae
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainersSunghyouk Bae
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern JavaSina Madani
 

Was ist angesagt? (20)

Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
모던자바의 역습
모던자바의 역습모던자바의 역습
모던자바의 역습
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 
Core Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug HuntCore Java - Quiz Questions - Bug Hunt
Core Java - Quiz Questions - Bug Hunt
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern Java
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 

Ähnlich wie Java 7 New Features

Ähnlich wie Java 7 New Features (20)

Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
Core java
Core javaCore java
Core java
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
Testing basics for developers
Testing basics for developersTesting basics for developers
Testing basics for developers
 
Java user group 2015 02-09-java8
Java user group 2015 02-09-java8Java user group 2015 02-09-java8
Java user group 2015 02-09-java8
 
Java user group 2015 02-09-java8
Java user group 2015 02-09-java8Java user group 2015 02-09-java8
Java user group 2015 02-09-java8
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
 
Java Intro
Java IntroJava Intro
Java Intro
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
 

Mehr von Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 

Mehr von Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 

Kürzlich hochgeladen

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Kürzlich hochgeladen (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

Java 7 New Features

  • 1. Java  7  New  Features   Jussi  Pohjolainen  
  • 2. 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  
  • 3. Oracle Certified Associate, Java SE 7 Programmer (OCA) •  No  prequisi6es   •  Dura8on  140  min,  number  of  ques8ons  90,   passing  score  77%   •  Price  200  –  300  e  
  • 4. 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  
  • 5. 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  
  • 6. OCP: Exam Topics •  Java  Class  Design   •  Java  File  I/O  (NIO.2)   •  Advanced  Class  Design   •  Building  Database   •  OO  Principles   Applica8ons  with  JDBC   •  Generics  and  Collec8on   •  Threads   •  String  processing   •  Concurrency   •  Excep8ons  and   •  Localiza8on   Asser8ons   •  Java  I/O  Fundamentals    
  • 7. 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  
  • 8. Upgrade  Exam  Topics   •  Language  Enhancements   •  Concurrency   –  Project  Coin   –  Atomic  variables,  locks,   •  Design  pa@erns   executors,  fork/join   –  Singleton,  composi8on,  DAO,   •  Localiza6on   factory   –  Locales,  resource  bundles   •  Database  Applica6ons  with  JDBC   •  Java  File  I/O  (NIO.2)   –  JDBC  API:  RowSetProvider,   –  Path  and  Files  -­‐  classes   RowSetFactory,  new  RowSet   interfaces  
  • 9.
  • 10. (RECAP)  JAVA  5  AND  6  
  • 11. 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)   …  
  • 12. New  Features   •  Java  SE  5   –  Generics   –  Autoboxing   –  Improved  looping  syntax   –  Annota8ons   –  …   •  Java  SE  6   –  XML  Processing  and  Web  Services   –  Scrip8ng   –  JDBC  4.0   –  …    
  • 13. 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()); }
  • 15. 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()); }
  • 17. 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); }
  • 18. 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()); } }
  • 19. 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()); } }
  • 20. Java  1.4:  Lot  of  Coding   Integer a = new Integer(5); Integer b = new Integer(6); int aPrimitive = a.intValue(); Int bPrimitive = b.intValue();
  • 21. Autoboxing  Comes  to  Rescue!   class Main { public static void main(String [] args) { // Boxing Integer a = 2; // UnBoxing int s = 5 + a; } }
  • 22. 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()); } }
  • 23. 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); } } }
  • 25. 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; }
  • 26. 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); }
  • 27. 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  
  • 28. 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); } } }
  • 29. 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); } }
  • 30. 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()); } }
  • 31. 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"); } }
  • 32. 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"); } }
  • 33. 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  
  • 34. 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.      
  • 36. Example   @Author( name = ”Jussi Pohjolainen", ) class MyClass() { … }
  • 38. Example   @Author( name = ”Jussi Pohjolainen", date = ”2012-09-12" ) class MyClass() { … }
  • 39. 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 { }
  • 41. 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 { }
  • 43. Targets   // Annotation type import java.lang.annotation.*; @Target(ElementType.METHOD) @interface Something { String foo(); } class Foo { @Something(foo = "hello") public void method() { } }
  • 44. 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(); } }
  • 45. Other  Annota8ons  used  By  Compiler   •  @Depricated –  Gives  warning  if  when   depricated  method  or  class  is  used   •  @SuppressWarnings –  Suppress  all  warnings   that  would  normally  generate  
  • 46. 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); } }
  • 47.
  • 48. 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); } }
  • 49. User  Input:  Scanner   Scanner in = new Scanner(System.in); int a = in.nextInt(); String b = in.nextLine();
  • 50. Java  6:  XML  &  Web  Services   •  Easy  way  of  crea8ng  Web  Services   •  Expose  web  service  with  a  simple  annota8on    
  • 51. 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; } }
  • 52. Server   package hello; import javax.xml.ws.Endpoint; class Publish { public static void main(String[] args) { Endpoint.publish( "http://localhost:8080/circlefunctions", new CircleFunctions()); } }
  • 53. Generate  Stub  Files   •  Generate  stub  files:   –  wsgen –cp . hello.CircleFunctions
  • 54.
  • 55. 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  
  • 56. 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(); } } }
  • 57. Java  6:  GUI   •  Faster  Splash  Screens   –  SplashScreen  class   –  java -splash:java-logo.jpeg Main •  System  tray  support   •  Wri8ng  of  Gif  -­‐  files  
  • 58. 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  
  • 63. ij   •  The  ij  is  an  interac8ve  scrip8ng  tool   •  Queries  against  a  Derby  database   •  Can  be  started  with  “ij”  if  in  path  
  • 64.
  • 66. JAVA  7  NEW  FEATURES  
  • 67. 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  
  • 68. 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    
  • 69. 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)
  • 70. 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
  • 72. 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  
  • 73. 1.  Strings  in  switch   •  Now  you  can  use  Strings  in  switch  statement   •  No  duplicate  labels   •  No  null  labels    
  • 75. 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;
  • 77. 3.  Mul8-­‐catch   •  Defining  mul8ple  excep8ons  in  one  catch   block   •  Use  |  (or)  as  separator  between  excep8on   types   •  Simplify  excep6on  handling  
  • 79. 4.  Type  Inference   •  For  collec8ons,  no  need  to  repeat  the  generic   typing  (diamond)   –  Map<String, String> coll = new HashMap<>();
  • 80. 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…  
  • 81.
  • 82. Java  7  to  the  rescue!  
  • 83. 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  
  • 87. 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  
  • 88. 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”);
  • 89. 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  
  • 90. Demo:  Path  -­‐  class  
  • 91. java.nio.file.Files •  Features   –  Copy   –  Create  directories   –  Create  files   –  Create  links   –  Use  of  the  “temp”  –  folder   –  Delete   –  Aoributes  –  Modified/Owner/Permission   –  Read  /  Write  
  • 92. 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)
  • 95. 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!  
  • 96. 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)  
  • 99.
  • 100.
  • 101. 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!  
  • 102. 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  
  • 105.
  • 108. Swing  Enhancements   •  JLayer   •  Nimbus  Look  &  Feel   •  Shaped  and  Translucent  Windows  
  • 109. 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  
  • 111. About  Nimbus   •  Moved  to  standard  API  namespace:   javax.swing   •  Cross-­‐plavorm  look  and  feel   •  Uses  2D  Vector  Graphics   •  Highly  Customizable  
  • 112. Serng  Theme   •  When  star8ng   –  UIManager.setLookAndFeel("javax.swing.plaf.nimb us.NimbusLookAndFeel"); •  Amer  start   –  UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusL ookAndFeel"); –  SwingUtilities.updateComponentTreeUI(this);
  • 115. Replace  Default  Color   •  UIManager.put("nimbusBase", new Color(...)); •  UIManager.put("nimbusBlueGrey", new Color(...)); •  UIManager.put("control", new Color(...));
  • 117. GUIs  in  the  future..  Java  Swing?  
  • 118. 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…  
  • 121. 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  
  • 122. 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!)  
  • 123. InvokeDynamic   •  Possible  to  call  methods  that  were  not  known   compile  8me!   •  You  can  use  API  to  use  bytecode  command   invokedynamic  
  • 125. Determing  the  Method  in  run8me  
  • 126. What  is  the  use?   •  For  normal  coding,  rare  uses   •  Some  u8li8es  (reflec8on)   •  For  future:  Virtual  machine  supports  different   languages!  Scrip8ng  languages  
  • 128. CONCURRENCY  UPDATES:        FORK/JOIN  
  • 129. 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  
  • 130. 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)  
  • 131. 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!    
  • 132. 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 }
  • 133. 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.  
  • 134. 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.    
  • 137. 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() {...} }
  • 139.
  • 142. Virtual  Machine  Updates   •  invokedynamic   •  New  garbage  collector  algorithm:  G1  
  • 143. 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  
  • 144. 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  
  • 145. 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.  
  • 146. 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.  
  • 147. Serng  the  Algorithm   java -XX:+UseSerialGC MyApp java -XX:+UseParallelGC MyApp java -XX:+UseConcMarkSweepGC MyApp java -XX:+UseG1GC MyApp
  • 149. JDBC  4.1   1.  AutoClosable:  Connec8on,  ResultSet,   Statement   2.  RowSet  1.1:  RowSetFactory  –  easy  crea8on  of   JdbcRowSet  
  • 150. Automa8cally  Close  Resources   •  Automa8cally  close:   –  java.sql.Connection –  java.sql.Statement –  java.sql.ResultSet
  • 151. 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); }
  • 152. 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(); } } }
  • 153. 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  
  • 154. 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  
  • 155. 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(); }
  • 157.
  • 158. Some  of  Proposed  content   •  Project  Jigsaw   •  Project  Lambda   •  JavaFX  3.0   •  Device  Support   –  Mul8-­‐touch,  Camera,  Loca8on,  Compass,   Accelerometer    
  • 159. 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; }
  • 160. Lambda   •  Perhaps  the  most  important  language  change:   Lambda  expressions  
  • 161. Mo8va8on   class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { //do something } } class UIBuilder { public UIBuilder() { button.addActionListener(new ButtonHandler()); } }
  • 162. 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!  
  • 163. Lambda  Expression!   class UIBuilder { public UIBuilder() { button.addActionListener(ActionEvent e -> // do something ) } }
  • 164. Lambda  Expressions   •  Lambda  expressions  are  8ny  anonymous   methods   •  The  syntax   –  (type  parameter)  -­‐>  func8on_body   •  Example   –  (String  s1,  String  s2)  -­‐>  s1.length()  –  s2.length()  
  • 165. 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());