SlideShare uma empresa Scribd logo
1 de 45
Baixar para ler offline
Evolution Of
Java
From Java 5 to 8
I want CODE

Here it is
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.
Java 5

•

September 2004 (old!, almost 9 years)
o Annotations
o Generics
OLDER JAVA

JAVA 5

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);

Compiled, but exception at runtime!!

compilation error
Java 5
o

Autoboxing/unboxing
JAVA 5

List<Integer> values = new ArrayList<Integer>();
values.add(3);
int value=values.get(0);

Integer value;
int primitive;

BOXING

UNBOXING

value=primitive;

primitive=value
;

o Enumerations:


With generics the type can’t be a
primitive, but is not a problem

Automatic operation

Special data type that enables for a variable to be a set of
predefined constants
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;
private State state=State.CORRECT;
}
Assert.assertEquals("GREEN", state.getColor());
public String getColor() {
return color;
}
public static List<State> getStateValues() {
return Arrays.asList(INCOMPLETE, CORRECT,INCORRECT);
}

}
Java 5
o Static imports
OLDER JAVA
double r = Math.cos(Math.PI * theta);

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

o Foreach
OLDER JAVA

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 + "-";
}
Java 5
o Varargs
OLDER JAVA

JAVA 5

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

sum(2, 2)); //two numbers
sum(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;
}

public int sum(final int... numbers) {
int total = 0;
for (final int number :
numbers) {
total += number;
}
return total;
}
Java 6

•

December 2006
o No language changes
o Scripting support
o Improvements in Swing
o JDBC 4.0 support
o ...
Java 7

•

July 2011 (ok, now we are talking)
o JVM support for dynamic languages
o Binary integer literals/underscores
int num =

0b101

int million = 1_000_000
int telephone = 983_71_25_03

o

Varargs simplified
o Strings in switch
OLDER JAVA

STRINGS IN SWITCH - JAVA 7

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
o
Automatic resource management in trypublic void newFile() {
catch
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fos = new
FileOutputStream("path.txt");
dos = new DataOutputStream(fos);
dos.writeBytes("prueba");
TRY WITH RESOURCES (ARM) - JAVA 7
} catch (final IOException e) {
public boolean newFile() {
e.printStackTrace();
try (FileOutputStream fos = new
} finally { // close resources
FileOutputStream("path.txt");
try {
DataOutputStream dos = new DataOutputStream(fos);)
dos.close();
{
fos.close();
dos.writeBytes("prueba");
} catch (final IOException e) {
dos.writeBytes("rn");
e.printStackTrace();
} catch (final IOException e) {
}
e.printStackTrace();
}
}
}
}
o Diamond Operator
OLDER JAVA
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());
private ArrayList<String> getListOfValues() {
}
return new ArrayList<String>(Arrays.asList("value1",
return map;
"value2"));
}
}

DIAMOND OPERATOR - JAVA 7
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());
}
private ArrayList<String> getListOfValues() {
return map;
return new ArrayList<>(Arrays.asList("value1",
}
"value2"));
}
o Catch multiple exceptions
OLDER JAVA
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;
}

MULTI CATCH - JAVA 7
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;
}
Java 7

•

New File I/O
java.io.File

java.nio.file.Path
o Solves problems
o New methods to
manipulate files

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);
}
new file
final File file = new File(path);
file.createNewFile();

new file
final Path file= Paths.get(path);
Files.createFile(file);

write file

write 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");
}
read file
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");
}
}

delete file
file.delete();

readfile
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");
}

delete file
Files.delete(file);
Java 8

•

Spring 2014?
o PermGen space disappears, new Metaspace
 OutOfMemory errors disappear? -> not so fast
o

New methods in Collections (almost all lambdarelated)

o

Small changes everywhere (concurrency, generics,
String, File, Math)
Java 8

•

Interfaces with static and default methods
o

¿WTF?

o

Let’s look at Eclipse...
Java 8
OLDER JAVA
public interface
CalculatorInterfacePreJava8 {
Integer add(Integer x, Integer y);
// WTF do u think you are doing?
// static Integer convert(Integer x);

JAVA 8
public interface
CalculatorInterfaceJava8 {
default Integer add(Integer x, Integer
y) {
return x + y;
}

}
static Integer convert(Integer x) {
return x * MAGIC_CONSTANT;
}
}
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.
Java 8
OLDER JAVA
//Date oldDate = new Date(1984, 7, 8);
oldDate = Calendar.getInstance();
oldDate.set(1984, 7, 8);

JAVA 8
date =
LocalDate.of(1984, Month.AUGUST, 8);
dateTime = LocalDateTime.of(1984,
Month.AUGUST, 8, 13, 0);
Java 8
OLDER JAVA
oldDate.set(Calendar.DAY_OF_MONTH,
oldDate.get(Calendar.DAY_OF_MONT
H) - 2);

JAVA 8
LocalDate sixOfAugust =
date.minusDays(2);
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-thebox
Java 8

•

How can I find the number of years between
two dates

•

Get next wednesday

•

Calculate flight time
Java 8

•

Lambda expressions! (at last)
o

Anonymous functions with special properties
Java 8

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

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

(x, y) -> x + y
Java 8

() -> x
Java 8

System.out.println(message)
Java 8

Implements a functional interface
Java 8

Classic Iteration
Java 8
OLDER JAVA

JAVA 8
strings.forEach(this::doSometh

for (final String text : strings) {
doSomething(text);
}

ing);
Java 8

Classic Filtering (and no-reuse)
Java 8
OLDER JAVA
List<String> longWords = new
ArrayList<String>();
for (final String text : strings) {
if (text.length() > 3) {
longWords.add(text);
}
}

JAVA 8
List<String> longWords =
strings.stream().
filter(e -> e.length() > 3)
.collect(Collectors.<String>
toList());
Java 8

Streams!
Java 8
OLDER JAVA
Integer maxCool = 0;
User coolestUser = null;
for (User user : coolUsers) {
if (maxCool <=
user.getCoolnessFactor()) {
coolestUser = user;
}
}

JAVA 8
User coolestUser = coolUsers.stream().
reduce(this::coolest).get();
Java 8

Optional
Java 8

Infinite Streams (Lazy)
Java 8

Parallelizable Operations
Java 8

•
•
•
•
•
•

More expressive language
Generalization
Composability
Internal vs External iteration
Laziness & parallelism
Reusability
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.
References
•
•
•
•
•
•
•
•

Examples in github
JDK 8 early access & eclipse with Java 8 support (+plugin)
Slides that inspired this talk
Quick survey of Java 7 features
Quick survey of Java 8 features
New Date and Time API
Good presentation of Java 8
There is even a book (wait, Java 8 isn’t live yet!)
Evolution Of
Java
From Java 5 to 8

Mais conteúdo relacionado

Destaque

5 клас урок 8
5 клас урок 85 клас урок 8
5 клас урок 8Olga Sokolik
 
C1 Topic 1 Language and Communication
C1 Topic 1 Language and CommunicationC1 Topic 1 Language and Communication
C1 Topic 1 Language and CommunicationNina's Cabbages
 
Geografija 7-klas-bojko
Geografija 7-klas-bojkoGeografija 7-klas-bojko
Geografija 7-klas-bojkokreidaros1
 
BK 7210 Urban analysis and design principles – ir. Evelien Brandes
BK 7210 Urban analysis and design principles – ir. Evelien BrandesBK 7210 Urban analysis and design principles – ir. Evelien Brandes
BK 7210 Urban analysis and design principles – ir. Evelien Brandesjornvorn
 
Geografija 6-klas-skuratovych
Geografija 6-klas-skuratovychGeografija 6-klas-skuratovych
Geografija 6-klas-skuratovychkreidaros1
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web ArchitectureChamnap Chhorn
 

Destaque (6)

5 клас урок 8
5 клас урок 85 клас урок 8
5 клас урок 8
 
C1 Topic 1 Language and Communication
C1 Topic 1 Language and CommunicationC1 Topic 1 Language and Communication
C1 Topic 1 Language and Communication
 
Geografija 7-klas-bojko
Geografija 7-klas-bojkoGeografija 7-klas-bojko
Geografija 7-klas-bojko
 
BK 7210 Urban analysis and design principles – ir. Evelien Brandes
BK 7210 Urban analysis and design principles – ir. Evelien BrandesBK 7210 Urban analysis and design principles – ir. Evelien Brandes
BK 7210 Urban analysis and design principles – ir. Evelien Brandes
 
Geografija 6-klas-skuratovych
Geografija 6-klas-skuratovychGeografija 6-klas-skuratovych
Geografija 6-klas-skuratovych
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 

Mais de Javier Gamarra

Performance myths in android
Performance myths in androidPerformance myths in android
Performance myths in androidJavier Gamarra
 
Cambiar una empresa con juegos ágiles
Cambiar una empresa con juegos ágilesCambiar una empresa con juegos ágiles
Cambiar una empresa con juegos ágilesJavier Gamarra
 
5 meses de juegos ágiles
5 meses de juegos ágiles5 meses de juegos ágiles
5 meses de juegos ágilesJavier Gamarra
 
Arduino - Cuarta sesión
Arduino - Cuarta sesiónArduino - Cuarta sesión
Arduino - Cuarta sesiónJavier Gamarra
 
Arduino - Tercera sesión
Arduino - Tercera sesiónArduino - Tercera sesión
Arduino - Tercera sesiónJavier Gamarra
 
Hibernate - JPA @luce 5
Hibernate - JPA @luce 5Hibernate - JPA @luce 5
Hibernate - JPA @luce 5Javier Gamarra
 
Hibernate - JPA @luce 4
Hibernate - JPA @luce 4Hibernate - JPA @luce 4
Hibernate - JPA @luce 4Javier Gamarra
 
Hibernate - JPA @luce 3
Hibernate - JPA @luce 3Hibernate - JPA @luce 3
Hibernate - JPA @luce 3Javier Gamarra
 
Hibernate - JPA @luce 2
Hibernate - JPA @luce 2Hibernate - JPA @luce 2
Hibernate - JPA @luce 2Javier Gamarra
 

Mais de Javier Gamarra (15)

Performance myths in android
Performance myths in androidPerformance myths in android
Performance myths in android
 
RxJava in practice
RxJava in practice RxJava in practice
RxJava in practice
 
Cambiar una empresa con juegos ágiles
Cambiar una empresa con juegos ágilesCambiar una empresa con juegos ágiles
Cambiar una empresa con juegos ágiles
 
New Android Languages
New Android LanguagesNew Android Languages
New Android Languages
 
5 meses de juegos ágiles
5 meses de juegos ágiles5 meses de juegos ágiles
5 meses de juegos ágiles
 
Opinionated android
Opinionated androidOpinionated android
Opinionated android
 
Arduino - Cuarta sesión
Arduino - Cuarta sesiónArduino - Cuarta sesión
Arduino - Cuarta sesión
 
Arduino - Tercera sesión
Arduino - Tercera sesiónArduino - Tercera sesión
Arduino - Tercera sesión
 
Hibernate - JPA @luce 5
Hibernate - JPA @luce 5Hibernate - JPA @luce 5
Hibernate - JPA @luce 5
 
Hibernate - JPA @luce 4
Hibernate - JPA @luce 4Hibernate - JPA @luce 4
Hibernate - JPA @luce 4
 
Hibernate - JPA @luce 3
Hibernate - JPA @luce 3Hibernate - JPA @luce 3
Hibernate - JPA @luce 3
 
Hibernate - JPA @luce 2
Hibernate - JPA @luce 2Hibernate - JPA @luce 2
Hibernate - JPA @luce 2
 
Hibernate - JPA @luce
Hibernate - JPA @luceHibernate - JPA @luce
Hibernate - JPA @luce
 
Codemotion 2013
Codemotion 2013Codemotion 2013
Codemotion 2013
 
CAS 2013
CAS 2013CAS 2013
CAS 2013
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Último (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Evolution of Java, from Java 5 to 8

  • 3. 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.
  • 4. Java 5 • September 2004 (old!, almost 9 years) o Annotations o Generics OLDER JAVA JAVA 5 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); Compiled, but exception at runtime!! compilation error
  • 5. Java 5 o Autoboxing/unboxing JAVA 5 List<Integer> values = new ArrayList<Integer>(); values.add(3); int value=values.get(0); Integer value; int primitive; BOXING UNBOXING value=primitive; primitive=value ; o Enumerations:  With generics the type can’t be a primitive, but is not a problem Automatic operation Special data type that enables for a variable to be a set of predefined constants
  • 6. 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; private State state=State.CORRECT; } Assert.assertEquals("GREEN", state.getColor()); public String getColor() { return color; } public static List<State> getStateValues() { return Arrays.asList(INCOMPLETE, CORRECT,INCORRECT); } }
  • 7. Java 5 o Static imports OLDER JAVA double r = Math.cos(Math.PI * theta); JAVA 5 double r = Math.cos(PI * theta); o Foreach OLDER JAVA 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 + "-"; }
  • 8. Java 5 o Varargs OLDER JAVA JAVA 5 sumTwo(2, 2)); //two numbers sumThree(2, 2, 2)); //three numbers sum(2, 2)); //two numbers sum(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; } public int sum(final int... numbers) { int total = 0; for (final int number : numbers) { total += number; } return total; }
  • 9. Java 6 • December 2006 o No language changes o Scripting support o Improvements in Swing o JDBC 4.0 support o ...
  • 10. Java 7 • July 2011 (ok, now we are talking) o JVM support for dynamic languages o Binary integer literals/underscores int num = 0b101 int million = 1_000_000 int telephone = 983_71_25_03 o Varargs simplified
  • 11. o Strings in switch OLDER JAVA STRINGS IN SWITCH - JAVA 7 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"; } }
  • 12. OLDER JAVA o Automatic resource management in trypublic void newFile() { catch FileOutputStream fos = null; DataOutputStream dos = null; try { fos = new FileOutputStream("path.txt"); dos = new DataOutputStream(fos); dos.writeBytes("prueba"); TRY WITH RESOURCES (ARM) - JAVA 7 } catch (final IOException e) { public boolean newFile() { e.printStackTrace(); try (FileOutputStream fos = new } finally { // close resources FileOutputStream("path.txt"); try { DataOutputStream dos = new DataOutputStream(fos);) dos.close(); { fos.close(); dos.writeBytes("prueba"); } catch (final IOException e) { dos.writeBytes("rn"); e.printStackTrace(); } catch (final IOException e) { } e.printStackTrace(); } } } }
  • 13. o Diamond Operator OLDER JAVA 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()); private ArrayList<String> getListOfValues() { } return new ArrayList<String>(Arrays.asList("value1", return map; "value2")); } } DIAMOND OPERATOR - JAVA 7 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()); } private ArrayList<String> getListOfValues() { return map; return new ArrayList<>(Arrays.asList("value1", } "value2")); }
  • 14. o Catch multiple exceptions OLDER JAVA 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; } MULTI CATCH - JAVA 7 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; }
  • 15. Java 7 • New File I/O java.io.File java.nio.file.Path o Solves problems o New methods to manipulate files 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); }
  • 16. new file final File file = new File(path); file.createNewFile(); new file final Path file= Paths.get(path); Files.createFile(file); write file write 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"); }
  • 17. read file 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"); } } delete file file.delete(); readfile 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"); } delete file Files.delete(file);
  • 18. Java 8 • Spring 2014? o PermGen space disappears, new Metaspace  OutOfMemory errors disappear? -> not so fast o New methods in Collections (almost all lambdarelated) o Small changes everywhere (concurrency, generics, String, File, Math)
  • 19. Java 8 • Interfaces with static and default methods o ¿WTF? o Let’s look at Eclipse...
  • 20. Java 8 OLDER JAVA public interface CalculatorInterfacePreJava8 { Integer add(Integer x, Integer y); // WTF do u think you are doing? // static Integer convert(Integer x); JAVA 8 public interface CalculatorInterfaceJava8 { default Integer add(Integer x, Integer y) { return x + y; } } static Integer convert(Integer x) { return x * MAGIC_CONSTANT; } }
  • 21. 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.
  • 22. Java 8 OLDER JAVA //Date oldDate = new Date(1984, 7, 8); oldDate = Calendar.getInstance(); oldDate.set(1984, 7, 8); JAVA 8 date = LocalDate.of(1984, Month.AUGUST, 8); dateTime = LocalDateTime.of(1984, Month.AUGUST, 8, 13, 0);
  • 23. Java 8 OLDER JAVA oldDate.set(Calendar.DAY_OF_MONTH, oldDate.get(Calendar.DAY_OF_MONT H) - 2); JAVA 8 LocalDate sixOfAugust = date.minusDays(2);
  • 24. 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-thebox
  • 25. Java 8 • How can I find the number of years between two dates • Get next wednesday • Calculate flight time
  • 26. Java 8 • Lambda expressions! (at last) o Anonymous functions with special properties
  • 27. Java 8 (int x, int y) -> { return x + y; }
  • 28. Java 8 (x, y) -> { return x + y; }
  • 29. Java 8 (x, y) -> x + y
  • 32. Java 8 Implements a functional interface
  • 34. Java 8 OLDER JAVA JAVA 8 strings.forEach(this::doSometh for (final String text : strings) { doSomething(text); } ing);
  • 35. Java 8 Classic Filtering (and no-reuse)
  • 36. Java 8 OLDER JAVA List<String> longWords = new ArrayList<String>(); for (final String text : strings) { if (text.length() > 3) { longWords.add(text); } } JAVA 8 List<String> longWords = strings.stream(). filter(e -> e.length() > 3) .collect(Collectors.<String> toList());
  • 38. Java 8 OLDER JAVA Integer maxCool = 0; User coolestUser = null; for (User user : coolUsers) { if (maxCool <= user.getCoolnessFactor()) { coolestUser = user; } } JAVA 8 User coolestUser = coolUsers.stream(). reduce(this::coolest).get();
  • 42. Java 8 • • • • • • More expressive language Generalization Composability Internal vs External iteration Laziness & parallelism Reusability
  • 43. 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.
  • 44. References • • • • • • • • Examples in github JDK 8 early access & eclipse with Java 8 support (+plugin) Slides that inspired this talk Quick survey of Java 7 features Quick survey of Java 8 features New Date and Time API Good presentation of Java 8 There is even a book (wait, Java 8 isn’t live yet!)