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
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.
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());
}
}
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
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;
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…
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
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)
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
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
115. Replace
Default
Color
• UIManager.put("nimbusBase", new Color(...));
• UIManager.put("nimbusBlueGrey", new Color(...));
• UIManager.put("control", new Color(...));
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
126. What
is
the
use?
• For
normal
coding,
rare
uses
• Some
u8li8es
(reflec8on)
• For
future:
Virtual
machine
supports
different
languages!
Scrip8ng
languages
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() {...}
}
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.
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
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());