Those are the slides for my presentation at OracleCode One 2018.
Java is moving faster and faster. A lot of features are not as known as they should be.
Let's review together the ones I think you've missed in old versions.
Then I will kickstart you on 9, 10 and 11 features that you never had time to look at.
16. 16
TL;DR
OracleJDK: Free and supported to 6 months
LTS versions have extended ($$$) support by Oracle
Identical to OpenJDK when free
OpenJDK: Free forever, not supported after 6 months
Built by https://adoptopenjdk.net/
Other JVMs (Azul, IBM, RedHat, etc.)
Supported by their vendor as they wish
A lot of “May” and “Possibly” in the party line
https://medium.com/@javachampions/java-is-still-free-
c02aef8c9e04
17. 17
Funny fact
Java 9 è Java 17.9
Java 10 è Java 18.3
Java 11 è Java 18.9
java version "11-ea" 2018-09-25
Java(TM) SE Runtime Environment 18.9 (build 11-ea+26)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11-ea+26, mixed mode)
20. 20
/**
* Counts the number of stack frames in this thread. The thread must
* be suspended.
*
* @return the number of stack frames in this thread.
* @throws IllegalThreadStateException if this thread is not
* suspended.
* @deprecated The definition of this call depends on {@link #suspend},
* which is deprecated. Further, the results of this call
* were never well-defined.
* This method is subject to removal in a future version of Java SE.
* @see StackWalker
*/
@Deprecated(since="1.2", forRemoval=true)
public native int countStackFrames();
27. 27
JAVA 5 GAVE THE GENERIC
TYPES TO THE WORLD
(and also annotations, concurrent collections, enum types, for
each, static imports and so on and so on)
38. 38
Auto Closeable
Before
InputStream in = new FileInputStream("allo.txt");
try {
// … do stuff
} finally {
try { in.close(); } catch(IOException e) {}
}
After
try(InputStream in = new FileInputStream("allo.txt")) {
// … do stuff
}
39. 39
Auto Closeable
Real code you should do
InputStream in = new FileInputStream("allo.txt");
try {
// … do stuff
in.close();
} catch(IOException e) {
try {
in.close();
} catch(IOException e1) {
e.addSuppressed(e1);
}
throw e;
}
42. 42
JAVA 8: LAMBDA!
(and also a new date API, default methods, metaspace, Nashorn,
JavaFX and CompletableFuture)
43. 43
Base64 ;-)
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class Base64s {
public static void main(String[] args) {
final String text = "Base64 finally in Java 8!";
final String encoded = Base64
.getEncoder()
.encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
System.out.println( encoded );
final String decoded = new String(
Base64.getDecoder().decode( encoded ),
StandardCharsets.UTF_8 );
System.out.println( decoded );
}
}
44. 44
Date / Time API
Core ideas:
Immutable
A time is a time, a date is a date. Not always both (like java.util.Date)
Not everyone uses the same calendar (the same Chronology)
LocalDate, LocalTime, LocalDateTime à Local. No time zone
OffsetDateTime, OffsetTime à Time with an offset from
Greenwich
ZonedDateTime à LocalDateTime with a time zone
Duration, Period à Time span
Instant à Timestamp
Formatting à Easy and thread-safe formatting
45. 45
Date / Time API (example)
LocalDateTime now = LocalDateTime.now();
String thatSpecialDay = now
.withDayOfMonth(1)
.atZone(ZoneId.of("Europe/Paris"))
.plus(Duration.ofDays(5))
.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
System.out.println(thatSpecialDay);
Output
2016-09-06T17:45:22.488+01:00[Europe/Paris]
47. 47
(also written as λ-calculus) is a formal system in
mathematical logic for expressing computation based
on function abstraction and application using variable
binding and substitution. It is a universal model of
computation that can be used to simulate any single-
taped Turing machine and was first introduced by
mathematician Alonzo Church in the 1930s as part of an
investigation into the foundations of mathematics.
Lambda calculus
48. 48
This is a function:
This is a lambda:
Lambda calculus
51. 51
Implicit final
List<String> list = new ArrayList<>();
String greeting = "Hello "; // no final required
list.forEach(s -> System.out.println(greeting + s));
list.forEach(new Consumer<String>() {
@Override public void accept(String s) {
System.out.println(greeting + s);
}
});
list.forEach(s -> greeting = “Hi”); // won’t compile
52. 52
Interface default methods
public interface List<E> extends
Collection<E> {
default void replaceAll(UnaryOperator<E>
operator) {
// …
}
}
public interface A {
default void foo() { }
}
public interface B{
default void foo() { }
}
public class C implements A, B {} // forbidden
public class C implements A, B { // allowed
public void foo() { }
}
public static class D implements A, B { //
allowed
public void foo() {
A.super.foo();
}
}
54. 54
Mustache vol. 2
Map<Long, Person> persons = Map.of(
1L, new Person(12, "Marc"),
2L, new Person(58, "Pierre”)
);
persons.entrySet().stream()
.map(entry -> new Object() {
long id = entry.getKey();
String name = entry.getValue().getName();
})
.forEach(tuple -> {
System.out.println(tuple.id + ": " + tuple.name);
});
}
55. 55
Everything is a lambda
public interface MyInterface {
int foo();
}
public void bar(MyInterface i) {
System.out.println(i.foo());
}
bar(() -> 4);
bar(new MyInterface() {
@Override public int foo() {
return 4;
}
});
JButton btn = new JButton();
btn.addActionListener(e -> {});
But it’s better to flag them
with
@FunctionalInterface
56. 56
Method references
public static class Passenger {
public void inboard(Train train) {
System.out.println("Inboard " + train);
}
}
public static class Train {
public static Train create(Supplier< Train > supplier)
{
return supplier.get();
}
public static void paintBlue(Train train) {
System.out.println("Painted blue " + train);
}
public void repair() {
System.out.println( "Repaired " + this);
}
}
Train train = Train.create(Train::new); // constructor
List<Train> trains = Arrays.asList(train);
trains.forEach(Train::paintBlue); // static
method
trains.forEach(Train::repair); // instance
method
Passenger p = new Passenger();
trains.forEach(p::inboard); // instance
method taking this in param
trains.forEach(System.out::println); // useful!
57. 57
Upside Down
public class MethodTest {
public class Foo {
static final String ERR_MESSAGE = "bad";
public void doIt() throws IllegalStateException {
throw new IllegalStateException(ERR_MESSAGE);
}
}
@Test
public void test() {
Foo foo = new Foo();
Throwable t = captureThrowable(foo::doIt);
assertThat(t)
.isInstanceOf(IllegalStateException.class)
.hasMessage(Foo.ERR_MESSAGE);
}
public static Throwable captureThrowable(Runnable r) {
Throwable result = null;
59. 59
Functional programming
List<String> list = new ArrayList<>();
int sum= list
.stream()
.filter(s -> s.startsWith("a"))
.mapToInt(String::length)
.sum();
List<Integer> length = list
.stream()
.map(String::length)
.collect(Collectors.toList());
60. 60
Parallel
List<String> list = new ArrayList<>();
int sum = list
.parallelStream()
.filter(s -> s.startsWith("a"))
.mapToInt(String::length)
.sum();
Arrays.parallelSort(array);
69. 69
JAVA 11: CLEANUP
(and dynamic class-file constants, epsilon, java.xml, corba and
many J2EE modules removed, nashorn removed, ZGC, single file
program)
70. 70
Prepare to do some stretching
Java 8 Java 9 Java 10 Java 11
What any sane person will want his/her framework to support
71. 71
Prepare to do some stretching
Java 8 Java 9 Java 10 Java 11
What any sane person will want his/her framework to support
Unsafe.defineClass()
MethodHandles.defineClass()
Unsafe.defineClass()
removed
72. 72
Prepare to do some stretching
Java 8 Java 9 Java 10 Java 11
What any sane person will want his/her framework to support
import java.xml.bind
--add-modules javax.xml.bind
--module-path containing
jaxb-api-2.4.0-xxx.jar