SlideShare a Scribd company logo
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

More Related Content

What's hot

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
Andrey Karpov
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
Rafael Winterhalter
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
HamletDRC
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
Ruslan Shevchenko
 
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
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
GeeksLab Odessa
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
HamletDRC
 
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
Anton Arhipov
 
Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
John Stevenson
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
ASP.NET
ASP.NETASP.NET
ASP.NET
chirag patil
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
Stuart Roebuck
 
Beyond java8
Beyond java8Beyond java8
Beyond java8
Muhammad Durrah
 
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
PawanMM
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
AndreCharland
 
Kotlin
KotlinKotlin
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
jessitron
 
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
Anton Arhipov
 

What's hot (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
 

Viewers also liked

χαρακτηριστικα του συγχρονου περιβαλλοντος
χαρακτηριστικα του συγχρονου περιβαλλοντοςχαρακτηριστικα του συγχρονου περιβαλλοντος
χαρακτηριστικα του συγχρονου περιβαλλοντοςNikolaos Dougekos
 
1995 4ο διαβητολογικό 2
1995 4ο διαβητολογικό 21995 4ο διαβητολογικό 2
1995 4ο διαβητολογικό 2iosis1979
 
Kirjastonhoidon Perusteet Greenwell Matongon Mukaan
Kirjastonhoidon Perusteet Greenwell Matongon MukaanKirjastonhoidon Perusteet Greenwell Matongon Mukaan
Kirjastonhoidon Perusteet Greenwell Matongon MukaanMaru 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 berlinMarie eve
 
Bwfinland pori 2013 program
Bwfinland pori 2013   programBwfinland pori 2013   program
Bwfinland pori 2013 program
Sigrun Sigurjonsdottir
 

Viewers also liked (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
 

Similar to Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac

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
STX Next
 
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
Mattias Karlsson
 
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
Ganesh Samarthyam
 
Kotlin for Android Development
Kotlin for Android DevelopmentKotlin for Android Development
Kotlin for Android Development
Speck&Tech
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
Abbas Raza
 
core java
core javacore java
core java
Vinodh Kumar
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
PostgreSQL and PL/Java
PostgreSQL and PL/JavaPostgreSQL and PL/Java
PostgreSQL and PL/Java
Peter Eisentraut
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
Lars Marius Garshol
 
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?
Mario Camou Riveroll
 
jimmy hacking (at) Microsoft
jimmy hacking (at) Microsoftjimmy hacking (at) Microsoft
jimmy hacking (at) Microsoft
Jimmy Schementi
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
Tobias Lindaaker
 
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
Rafael Winterhalter
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
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
Trayan Iliev
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
Paul King
 
Clojure, Plain and Simple
Clojure, Plain and SimpleClojure, Plain and Simple
Clojure, Plain and Simple
Ben Mabey
 

Similar to 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
 

Recently uploaded

E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
ISH Technologies
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 

Recently uploaded (20)

E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit ParisNeo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
Neo4j - Product Vision and Knowledge Graphs - GraphSummit Paris
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Preparing Non - Technical Founders for Engaging a Tech Agency
Preparing Non - Technical Founders for Engaging  a  Tech AgencyPreparing Non - Technical Founders for Engaging  a  Tech Agency
Preparing Non - Technical Founders for Engaging a Tech Agency
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 

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. ?