SlideShare uma empresa Scribd logo
1 de 22
Tricky stuff
in java grammar and javac
About me
Marek Parfianowicz
• Gdańsk University of Technology, ETI, distributed software systems
• Senior Software Engineer at Lufthansa Systems (2004-2012)
• Support Engineer and Software Developer at Spartez (since 2012)
o main developer of the Atlassian Clover
• C/C++, Java, Groovy, Scala
Language tricks
“&” operator for casting
public class LambdaTest {
public static void main(String[] args) throws Exception {
Object o1 = (Runnable & Serializable) () ->
System.out.println("I’m a serializable lambda");
Object o2 = (Runnable) () ->
System.out.println("I’m NOT serializable!!!");
ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream());
out.writeObject(o1); // OK
out.writeObject(o2); // java.io.NotSerializableException
}
}
JDK5
“&” operator for generics
class MyClass<S extends Comparable & Runnable> {
S s;
MyClass(S s) { this.s = s; }
S getComparableRunner() { return s; }
static MyClass<ComparableRunner> create() {
return new MyClass<ComparableRunner>(new ComparableRunner());
}
}
class ComparableRunner implements Comparable, Runnable {
public void run() { }
public int compareTo(Object o) { return 0; }
}
// instead of:
abstract class ComparableRunnable
implements Comparable, Runnable { }
class MyClass<S extends ComparableRunnable> {
// ...
}
JDK5
“|” operator for multiple catch (1)
public void myCatch(String name) throws IOException {
try {
if (name.equals("First"))
throw new FirstException();
else
throw new SecondException();
} catch (FirstException | SecondException e) {
throw e;
}
} JDK7
“|” operator for multiple catch (2)
public void myRethrow(String name)
throws FirstException, SecondException {
try {
if (name.equals("First"))
throw new FirstException();
else
throw new SecondException();
} catch (IOException e) {
throw e;
}
} JDK7
Hexadecimal floats
• “P” for a binary exponent
• “D” and “F” for double and float
• write exact value avoiding decimal rounding problems
public class HexFloat {
double f3 = 0XAB1P0;
double f4 = 0Xab1aP+20;
double f5 = 0Xab1aP+20d;
float f7 = 0Xab1aP+3f;
}
JDK5
String in switch
public String switchWithString(String name) {
switch (name) {
case "Moon":
return "moon";
case "Sun":
return "star";
default:
return "unknown";
}
} JDK7
if (“Moon”.equals(a)) { … }
else if …
try (
zipFile = new java.util.zip.ZipFile(zipFileName);
bufferedWriter = java.nio.file.Files.newBufferedWriter(filePath, charset)
) {
// … make some stuff …
}
Try with resources
• java.lang.AutoCloseable
JDK7
Lambda functions (1)
Declaration of an argument. Calling lambda.
WAT?
// not possible :-(
void call((String -> void) consumer) {
consumer(“abc”);
}
import java.util.function.Consumer;
void call(Consumer<String> consumer) {
consumer.accept(“abc”);
}
JDK8
Lambda functions (2)
Making lambda serializable:
Runnable r = (Runnable & Serializable) () -> System.out.println(“Hello”);
Lambda in ternary expressions:
Callable<Integer> c1 = flag ? () -> 23 : () -> 42;
Lambda vs operator priorities:
Produce<Integer> o = z != 0 ? y -> y < 0 ? y + 1 : y - 1 : y -> 3 * y;
z != 0 ? (y) -> { return (y < 0 ? y+1 : y-1); }
: (y) -> { return 3 * y; }; JDK8
class WithLambdaRecursion {
static IntUnaryOperator factorial = i ->
i == 0 ? 1 : i * WithLambdaRecursion.factorial.map(i - 1);
}
Lambda functions (3)
Recursion in lambda functions:
class WithLambdaRecursion {
static IntUnaryOperator factorial = i ->
i == 0 ? 1 : i * factorial.map(i - 1);
} ERROR
JDK8
Method references - constructors
• object constructors
import java.util.function.Supplier;
Supplier<String> sup = String::new;
String emptyString = sup.get();
• array constructors
interface ProduceStringArray {
String[] produce(int n);
}
ProduceStringArray creator = String[]::new;
String[] stringArray = creator.produce(10); JDK8
Method references - constructors
• generic constructors
ArrayList::new // raw list
ArrayList::<String>new // forbidden
ArrayList<String>::new // generic list
ArrayList<String>::<String>new // superfluous, but OK
JDK8
Compiler quirks
Generics with autoboxing (1)
• A compiler bug? A feature?
• A branch condition with autoboxed Boolean declared as a generic type
interface Data {
public <T> T getValue();
}
public boolean testGetValue(Data source) {
// shall we expect “Object” for source.getValue()?
}
Generics with autoboxing (2)
// fails under JDK6, compiles under JDK7+
public boolean testGetValue(Data source) {
if (source.getValue()) // Implicit conversion to Boolean via autoboxing
...
}
// … but compilation of this code fails under JDK7 with a message:
// Error: Operator && cannot be applied to java.lang.Object, boolean
public boolean testGetValue(Data source) {
if (source.getValue() && true)
…
}
Generics with autoboxing (3)
> javap -c GenericsWithAutoboxing.class
...
public boolean testGetValue(Data);
Code:
0: aload_1
1: invokeinterface #2, 1 // InterfaceMethod Data.getValue:()Ljava/lang/Object;
6: checkcast #3 // class java/lang/Boolean
9: invokevirtual #4 // Method java/lang/Boolean.booleanValue:()Z
12: ifeq 17
15: iconst_1
16: ireturn
17: iconst_0
18: ireturn
Cast + generics
• Compiler bug; occurs in JDK6+JDK7; javac is unable to parse () with <>
public class Util {
@SuppressWarnings("unchecked")
public static <T> T cast(Object x) {
return (T) x;
}
static {
Util.<Object>cast(null); // OK
(Util.<Object>cast(null)).getClass(); // Error: illegal start of expression
}
}
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6481655
?
Thank you

Mais conteúdo relacionado

Mais procurados

AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
Duoyi Wu
 

Mais procurados (20)

Static analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesStatic analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutes
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
Javascript engine performance
Javascript engine performanceJavascript engine performance
Javascript engine performance
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
ASP.NET
ASP.NETASP.NET
ASP.NET
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Beyond java8
Beyond java8Beyond java8
Beyond java8
 
Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3Session 09 - OOP with Java - Part 3
Session 09 - OOP with Java - Part 3
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
 
Kotlin
KotlinKotlin
Kotlin
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloadingJEEConf 2017 - The hitchhiker’s guide to Java class reloading
JEEConf 2017 - The hitchhiker’s guide to Java class reloading
 

Destaque

χαρακτηριστικα του συγχρονου περιβαλλοντος
χαρακτηριστικα του συγχρονου περιβαλλοντοςχαρακτηριστικα του συγχρονου περιβαλλοντος
χαρακτηριστικα του συγχρονου περιβαλλοντος
Nikolaos Dougekos
 
1995 4ο διαβητολογικό 2
1995 4ο διαβητολογικό 21995 4ο διαβητολογικό 2
1995 4ο διαβητολογικό 2
iosis1979
 
Kirjastonhoidon Perusteet Greenwell Matongon Mukaan
Kirjastonhoidon Perusteet Greenwell Matongon MukaanKirjastonhoidon Perusteet Greenwell Matongon Mukaan
Kirjastonhoidon Perusteet Greenwell Matongon Mukaan
Maru Peltonen
 
El berlín del muro[2]
El berlín del muro[2]El berlín del muro[2]
El berlín del muro[2]
circusromanus
 
Londroid Akshay Performance
Londroid Akshay PerformanceLondroid Akshay Performance
Londroid Akshay Performance
Skills Matter
 
Berlin
BerlinBerlin
Berlin
Cerbin
 
Mein tag in berlin
Mein tag in berlinMein tag in berlin
Mein tag in berlin
Marie eve
 

Destaque (9)

χαρακτηριστικα του συγχρονου περιβαλλοντος
χαρακτηριστικα του συγχρονου περιβαλλοντοςχαρακτηριστικα του συγχρονου περιβαλλοντος
χαρακτηριστικα του συγχρονου περιβαλλοντος
 
1995 4ο διαβητολογικό 2
1995 4ο διαβητολογικό 21995 4ο διαβητολογικό 2
1995 4ο διαβητολογικό 2
 
Kirjastonhoidon Perusteet Greenwell Matongon Mukaan
Kirjastonhoidon Perusteet Greenwell Matongon MukaanKirjastonhoidon Perusteet Greenwell Matongon Mukaan
Kirjastonhoidon Perusteet Greenwell Matongon Mukaan
 
El berlín del muro[2]
El berlín del muro[2]El berlín del muro[2]
El berlín del muro[2]
 
Londroid Akshay Performance
Londroid Akshay PerformanceLondroid Akshay Performance
Londroid Akshay Performance
 
Berlin
BerlinBerlin
Berlin
 
Mein tag in berlin
Mein tag in berlinMein tag in berlin
Mein tag in berlin
 
Bwfinland pori 2013 program
Bwfinland pori 2013   programBwfinland pori 2013   program
Bwfinland pori 2013 program
 
Unger
UngerUnger
Unger
 

Semelhante a Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) Microsoft
Jimmy Schementi
 

Semelhante a Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac (20)

Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
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
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
core java
core javacore java
core java
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
PostgreSQL and PL/Java
PostgreSQL and PL/JavaPostgreSQL and PL/Java
PostgreSQL and PL/Java
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) Microsoft
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Rapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and KtorRapid Web API development with Kotlin and Ktor
Rapid Web API development with Kotlin and Ktor
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and Simple
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Último (20)

Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 

Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac

  • 1. Tricky stuff in java grammar and javac
  • 2. About me Marek Parfianowicz • Gdańsk University of Technology, ETI, distributed software systems • Senior Software Engineer at Lufthansa Systems (2004-2012) • Support Engineer and Software Developer at Spartez (since 2012) o main developer of the Atlassian Clover • C/C++, Java, Groovy, Scala
  • 4. “&” operator for casting public class LambdaTest { public static void main(String[] args) throws Exception { Object o1 = (Runnable & Serializable) () -> System.out.println("I’m a serializable lambda"); Object o2 = (Runnable) () -> System.out.println("I’m NOT serializable!!!"); ObjectOutputStream out = new ObjectOutputStream(new ByteArrayOutputStream()); out.writeObject(o1); // OK out.writeObject(o2); // java.io.NotSerializableException } } JDK5
  • 5. “&” operator for generics class MyClass<S extends Comparable & Runnable> { S s; MyClass(S s) { this.s = s; } S getComparableRunner() { return s; } static MyClass<ComparableRunner> create() { return new MyClass<ComparableRunner>(new ComparableRunner()); } } class ComparableRunner implements Comparable, Runnable { public void run() { } public int compareTo(Object o) { return 0; } } // instead of: abstract class ComparableRunnable implements Comparable, Runnable { } class MyClass<S extends ComparableRunnable> { // ... } JDK5
  • 6. “|” operator for multiple catch (1) public void myCatch(String name) throws IOException { try { if (name.equals("First")) throw new FirstException(); else throw new SecondException(); } catch (FirstException | SecondException e) { throw e; } } JDK7
  • 7. “|” operator for multiple catch (2) public void myRethrow(String name) throws FirstException, SecondException { try { if (name.equals("First")) throw new FirstException(); else throw new SecondException(); } catch (IOException e) { throw e; } } JDK7
  • 8. Hexadecimal floats • “P” for a binary exponent • “D” and “F” for double and float • write exact value avoiding decimal rounding problems public class HexFloat { double f3 = 0XAB1P0; double f4 = 0Xab1aP+20; double f5 = 0Xab1aP+20d; float f7 = 0Xab1aP+3f; } JDK5
  • 9. String in switch public String switchWithString(String name) { switch (name) { case "Moon": return "moon"; case "Sun": return "star"; default: return "unknown"; } } JDK7 if (“Moon”.equals(a)) { … } else if …
  • 10. try ( zipFile = new java.util.zip.ZipFile(zipFileName); bufferedWriter = java.nio.file.Files.newBufferedWriter(filePath, charset) ) { // … make some stuff … } Try with resources • java.lang.AutoCloseable JDK7
  • 11. Lambda functions (1) Declaration of an argument. Calling lambda. WAT? // not possible :-( void call((String -> void) consumer) { consumer(“abc”); } import java.util.function.Consumer; void call(Consumer<String> consumer) { consumer.accept(“abc”); } JDK8
  • 12. Lambda functions (2) Making lambda serializable: Runnable r = (Runnable & Serializable) () -> System.out.println(“Hello”); Lambda in ternary expressions: Callable<Integer> c1 = flag ? () -> 23 : () -> 42; Lambda vs operator priorities: Produce<Integer> o = z != 0 ? y -> y < 0 ? y + 1 : y - 1 : y -> 3 * y; z != 0 ? (y) -> { return (y < 0 ? y+1 : y-1); } : (y) -> { return 3 * y; }; JDK8
  • 13. class WithLambdaRecursion { static IntUnaryOperator factorial = i -> i == 0 ? 1 : i * WithLambdaRecursion.factorial.map(i - 1); } Lambda functions (3) Recursion in lambda functions: class WithLambdaRecursion { static IntUnaryOperator factorial = i -> i == 0 ? 1 : i * factorial.map(i - 1); } ERROR JDK8
  • 14. Method references - constructors • object constructors import java.util.function.Supplier; Supplier<String> sup = String::new; String emptyString = sup.get(); • array constructors interface ProduceStringArray { String[] produce(int n); } ProduceStringArray creator = String[]::new; String[] stringArray = creator.produce(10); JDK8
  • 15. Method references - constructors • generic constructors ArrayList::new // raw list ArrayList::<String>new // forbidden ArrayList<String>::new // generic list ArrayList<String>::<String>new // superfluous, but OK JDK8
  • 17. Generics with autoboxing (1) • A compiler bug? A feature? • A branch condition with autoboxed Boolean declared as a generic type interface Data { public <T> T getValue(); } public boolean testGetValue(Data source) { // shall we expect “Object” for source.getValue()? }
  • 18. Generics with autoboxing (2) // fails under JDK6, compiles under JDK7+ public boolean testGetValue(Data source) { if (source.getValue()) // Implicit conversion to Boolean via autoboxing ... } // … but compilation of this code fails under JDK7 with a message: // Error: Operator && cannot be applied to java.lang.Object, boolean public boolean testGetValue(Data source) { if (source.getValue() && true) … }
  • 19. Generics with autoboxing (3) > javap -c GenericsWithAutoboxing.class ... public boolean testGetValue(Data); Code: 0: aload_1 1: invokeinterface #2, 1 // InterfaceMethod Data.getValue:()Ljava/lang/Object; 6: checkcast #3 // class java/lang/Boolean 9: invokevirtual #4 // Method java/lang/Boolean.booleanValue:()Z 12: ifeq 17 15: iconst_1 16: ireturn 17: iconst_0 18: ireturn
  • 20. Cast + generics • Compiler bug; occurs in JDK6+JDK7; javac is unable to parse () with <> public class Util { @SuppressWarnings("unchecked") public static <T> T cast(Object x) { return (T) x; } static { Util.<Object>cast(null); // OK (Util.<Object>cast(null)).getClass(); // Error: illegal start of expression } } http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6481655
  • 21. ?