Evolution of Java, from Java 5 to 8

45
Evolution Of Java From Java 5 to 8

description

A recap of the evolution of Java starting with the JDK5 and finishing with the new api of date/time and lamdbas. The code is in github (https://github.com/nhpatt/evolution_of_java), showing how to do it in Java 5 and 8.

Transcript of Evolution of Java, from Java 5 to 8

Page 1: Evolution of Java, from Java 5 to 8

Evolution Of

Java

From Java 5 to 8

Page 2: Evolution of Java, from Java 5 to 8

I want CODE

Here it is

Page 3: Evolution of Java, from Java 5 to 8

State of the union

• Currently in Java 7

o Luce has some projects working with Java 7

(ipamms, aernova…), the rest of them are Java 6.

• Java 8 expected in spring 2014.

Page 4: Evolution of Java, from Java 5 to 8

Java 5

• September 2004 (old!, almost 9 years)

o Annotations

o Generics

List values = new ArrayList();

values.add("value 1");

values.add(3);

String value=(String) values.get(0);

String value2=(String) values.get(1);

List<String> values = new ArrayList<String>();

values.add("value 1");

values.add(new Integer(3));

String value= values.get(0);

Integer value1= values.get(1);

OLDER JAVA JAVA 5

Compiled, but exception at runtime!! compilation error

Page 5: Evolution of Java, from Java 5 to 8

Java 5

o Autoboxing/unboxing

List<Integer> values = new ArrayList<Integer>();

values.add(3);

int value=values.get(0);

JAVA 5

value=primitive;

BOXING

primitive=value

;

UNBOXINGAutomatic operation

With generics the type can’t be a

primitive, but is not a problem

Integer value;

int primitive;

o Enumerations: Special data type that enables for a variable to be a set of

predefined constants

Page 6: Evolution of Java, from Java 5 to 8

public enum State{

INCOMPLETE("Incompl","YELLOW"),CORRECT("Correct","GREEN"), INCORRECT("Incorrect","RED");

private String name;

private String color;

private State(final String name, final String color) {

this.name = name;

this.color=color;

}

public String getName() {

return name;

}

public String getColor() {

return color;

}

public static List<State> getStateValues() {

return Arrays.asList(INCOMPLETE, CORRECT,INCORRECT);

}

}

private State state=State.CORRECT;

Assert.assertEquals("GREEN", state.getColor());

Page 7: Evolution of Java, from Java 5 to 8

Java 5

String result = "";

for (int i = 0; i < values.size(); i++) {

result += values.get(i) + "-";

}

String result = "";

for (final String value : values) {

result += value + "-";

}

OLDER JAVA JAVA 5

o Foreach

o Static imports

double r = Math.cos(PI * theta);

OLDER JAVA JAVA 5

double r = Math.cos(Math.PI * theta);

Page 8: Evolution of Java, from Java 5 to 8

sumTwo(2, 2)); //two numbers

sumThree(2, 2, 2)); //three numbers

public int sumTwo(final int a, final int b) {

return a + b;

}

public int sumThree(final int a, final int b,

final int c) {

return a + b + c;

}

sum(2, 2)); //two numbers

sum(2, 2, 2)); //three numbers

public int sum(final int... numbers) {

int total = 0;

for (final int number :

numbers) {

total += number;

}

return total;

}

OLDER JAVA JAVA 5

o Varargs

Java 5

Page 9: Evolution of Java, from Java 5 to 8

Java 6

• December 2006

o No language changes

o Scripting support

o Improvements in Swing

o JDBC 4.0 support

o ...

Page 10: Evolution of Java, from Java 5 to 8

Java 7

• July 2011 (ok, now we are talking)

o JVM support for dynamic languages

o Binary integer literals/underscores

o Varargs simplified

int million = 1_000_000

int telephone = 983_71_25_03

int num = 0b101

Page 11: Evolution of Java, from Java 5 to 8

public String getColor (final String state) {

if (("correct".equals(state)) {

return "green";

} else if("incorrect".equals(state)) {

return "red";

} else if ("incomplete".equals(state)){

return "yellow";

} else {

return "white";

}

}

public String getColor(final String state) {

switch (state) {

case "correct":

return "green";

case "incorrect":

return "red";

case "incomplete":

return "yellow";

default:

return "white";

}

}

OLDER JAVA STRINGS IN SWITCH - JAVA 7

o Strings in switch

Page 12: Evolution of Java, from Java 5 to 8

public void newFile() {

FileOutputStream fos = null;

DataOutputStream dos = null;

try {

fos = new

FileOutputStream("path.txt");

dos = new DataOutputStream(fos);

dos.writeBytes("prueba");

} catch (final IOException e) {

e.printStackTrace();

} finally { // close resources

try {

dos.close();

fos.close();

} catch (final IOException e) {

e.printStackTrace();

}

}

}

public boolean newFile() {

try (FileOutputStream fos = new

FileOutputStream("path.txt");

DataOutputStream dos = new DataOutputStream(fos);)

{

dos.writeBytes("prueba");

dos.writeBytes("\r\n");

} catch (final IOException e) {

e.printStackTrace();

}

}

OLDER JAVA

TRY WITH RESOURCES (ARM) - JAVA 7

o Automatic resource management in try-

catch

Page 13: Evolution of Java, from Java 5 to 8

private Map<Integer, List<String>> createMapOfValues(final int... keys) {

final Map<Integer, List<String>> map = new HashMap<Integer,

List<String>>();

for (final int key : keys) {

map.put(key, getListOfValues());

}

return map;

}

private Map<Integer, List<String>> createMapOfValues(final int... keys) {

final Map<Integer, List<String>> map = new HashMap<>();

for (final int key : keys) {

map.put(key, getListOfValues());

}

return map;

}

OLDER JAVA

DIAMOND OPERATOR - JAVA 7

private ArrayList<String> getListOfValues() {

return new ArrayList<String>(Arrays.asList("value1",

"value2"));

}

private ArrayList<String> getListOfValues() {

return new ArrayList<>(Arrays.asList("value1",

"value2"));

}

o Diamond Operator

Page 14: Evolution of Java, from Java 5 to 8

public double divide() {

double result = 0d;

try {

int a = Integer.parseInt(num1);

int b = Integer.parseInt(num2);

result = a / b;

} catch (NumberFormatException ex1) {

System.out.println("invalid number");

} catch (ArithmeticException ex2) {

System.out.println("zero");

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

public double divide(){

double result = 0d;

try {

int a = Integer.parseInt(num1);

int b = Integer.parseInt(num2);

result = a / b;

} catch (NumberFormatException|ArithmeticException ex){

System.out.println("invalid number or zero");

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

OLDER JAVA

MULTI CATCH - JAVA 7

o Catch multiple exceptions

Page 15: Evolution of Java, from Java 5 to 8

Java 7

• New File I/O

Path path = Paths.get("C:\\Users/Pili/Documents/f.txt");

path.getFileName(); -> "f.txt"

path.getName(0); -> "Users"

path.getNameCount(); -> 4

path.subpath(0, 2); -> "Users/Pili"

path.getParent(); -> "C:\\Users/Pili/Documents"

path.getRoot(); -> "C:\\"

path.startsWith("C:\\Users"); -> true

for (final Path name : path) {

System.out.println(name);

}

java.io.File

o Solves problems

o New methods to

manipulate files

java.nio.file.Path

Page 16: Evolution of Java, from Java 5 to 8

final File file = new File(path);

file.createNewFile();

final Path file= Paths.get(path);

Files.createFile(file);

new file new file

BufferedWriter bw = null;

try {

bw =new BufferedWriter(new FileWriter(file));

bw.write("Older Java: This is first line");

bw.newLine();

bw.write("Older Java: This is second line");

} catch (final IOException e) {

e.printStackTrace();

} finally {

try {

bw.close();

} catch (final IOException ex) {

System.out.println("Error");

}

}

try (BufferedWriter writer =

Files.newBufferedWriter(file,Charset.defaultCharset())

) {

writer.append("Java 7: This is first line");

writer.newLine();

writer.append("Java 7: This is second line");

} catch (final IOException exception) {

System.out.println("Error");

}

write file write file

Page 17: Evolution of Java, from Java 5 to 8

BufferedReader br = null;

try {

br = new BufferedReader(new FileReader(file));

String content;

while ((content = br.readLine()) != null) {

System.out.println(content);

}

} catch (final IOException e) {

e.printStackTrace();

} finally {

try{

br.close();

} catch (final IOException ex) {

System.out.println("Error");

}

}

try (BufferedReader reader = Files.newBufferedReader

(file, Charset.defaultCharset())) {

String content= "";

while ((content = reader.readLine()) != null) {

System.out.println(content);

}

} catch (final IOException exception) {

System.out.println("Error");

}

read file readfile

file.delete(); Files.delete(file);

delete file delete file

Page 18: Evolution of Java, from Java 5 to 8

Java 8

• Spring 2014?

o PermGen space disappears, new Metaspace

OutOfMemory errors disappear? -> not so fast

o New methods in Collections (almost all lambda-

related)

o Small changes everywhere (concurrency, generics,

String, File, Math)

Page 19: Evolution of Java, from Java 5 to 8

Java 8

• Interfaces with static and default methods

o ¿WTF?

o Let’s look at Eclipse...

Page 20: Evolution of Java, from Java 5 to 8

Java 8

public interface

CalculatorInterfacePreJava8 {

Integer add(Integer x, Integer y);

// WTF do u think you are doing?

// static Integer convert(Integer x);

}

public interface

CalculatorInterfaceJava8 {

default Integer add(Integer x, Integer

y) {

return x + y;

}

static Integer convert(Integer x) {

return x * MAGIC_CONSTANT;

}

}

OLDER JAVA JAVA 8

Page 21: Evolution of Java, from Java 5 to 8

Java 8

• new Date and Time API (joda inspired)

o Current was based on currentTimeMillis, Date and

Calendar.

o New one is based on continuous time and human

time.

o Inmutable.

Page 22: Evolution of Java, from Java 5 to 8

Java 8

//Date oldDate = new Date(1984, 7, 8);

oldDate = Calendar.getInstance();

oldDate.set(1984, 7, 8);

date =

LocalDate.of(1984, Month.AUGUST, 8);

dateTime = LocalDateTime.of(1984,

Month.AUGUST, 8, 13, 0);

OLDER JAVA JAVA 8

Page 23: Evolution of Java, from Java 5 to 8

Java 8

oldDate.set(Calendar.DAY_OF_MONTH,

oldDate.get(Calendar.DAY_OF_MONT

H) - 2);

LocalDate sixOfAugust =

date.minusDays(2);

OLDER JAVA JAVA 8

Page 24: Evolution of Java, from Java 5 to 8

Java 8

• Easier to add hours/days/… (plusDaysTest)

• Easier to set date at midnight/noon (atStartOfDayTest)

• Similar way to use instant time

• Easier to format and ISO dates supported right-out-the-

box

• Months/days start at 1!

Page 26: Evolution of Java, from Java 5 to 8

Java 8

• Lambda expressions! (at last)

o Anonymous functions with special properties

Page 27: Evolution of Java, from Java 5 to 8

Java 8

(int x, int y) -> { return x + y; }

Page 28: Evolution of Java, from Java 5 to 8

Java 8

(x, y) -> { return x + y; }

Page 29: Evolution of Java, from Java 5 to 8

Java 8

(x, y) -> x + y

Page 30: Evolution of Java, from Java 5 to 8

Java 8

() -> x

Page 31: Evolution of Java, from Java 5 to 8

Java 8

System.out.println(message)

Page 32: Evolution of Java, from Java 5 to 8

Java 8

Implements a functional interface

Page 33: Evolution of Java, from Java 5 to 8

Java 8

Classic Iteration

Page 34: Evolution of Java, from Java 5 to 8

Java 8

for (final String text : strings) {

doSomething(text);

}

strings.forEach(this::doSometh

ing);

OLDER JAVA JAVA 8

Page 35: Evolution of Java, from Java 5 to 8

Java 8

Classic Filtering (and no-reuse)

Page 36: Evolution of Java, from Java 5 to 8

Java 8

List<String> longWords = new

ArrayList<String>();

for (final String text : strings) {

if (text.length() > 3) {

longWords.add(text);

}

}

List<String> longWords =

strings.stream().

filter(e -> e.length() > 3)

.collect(Collectors.<String>

toList());

OLDER JAVA JAVA 8

Page 37: Evolution of Java, from Java 5 to 8

Java 8

Streams!

Page 38: Evolution of Java, from Java 5 to 8

Java 8

Integer maxCool = 0;

User coolestUser = null;

for (User user : coolUsers) {

if (maxCool <=

user.getCoolnessFactor()) {

coolestUser = user;

}

}

User coolestUser = coolUsers.stream().

reduce(this::coolest).get();

OLDER JAVA JAVA 8

Page 39: Evolution of Java, from Java 5 to 8

Java 8

Optional

Page 40: Evolution of Java, from Java 5 to 8

Java 8

Infinite Streams (Lazy)

Page 41: Evolution of Java, from Java 5 to 8

Java 8

Parallelizable Operations

Page 42: Evolution of Java, from Java 5 to 8

Java 8

• More expressive language

• Generalization

• Composability

• Internal vs External iteration

• Laziness & parallelism

• Reusability

Page 43: Evolution of Java, from Java 5 to 8

The Future?

• 2014 is right around the corner…

• Java 9, 2016?

o Modularization (project Jigsaw)

o Money and Currency API

o Hope it is not this.

Page 45: Evolution of Java, from Java 5 to 8

Evolution Of

Java

From Java 5 to 8