On Github ThatJoeMoore / TeamJava8Lesson
Grab the slides at http://tiny.cc/OITJava8
NOT the Java we know and love-hate.
public interface MyInterface {
void myMethod();
//Same as:
public void myMethod();
}
End-of-life: April 14, 2015
if (string.equals("hi") || string.equals("bye")) {
return "ciao";
} else if (string.equals("hello")) {
return "salve";
} else {
return "non capisco " + string;
}
switch (string) {
case "hi":
case "bye":
return "ciao";
case "hello":
return "salve";
default:
return "non capisco " + string;
}
No null checking - throws a NullPointerException
Case-sensitive
Don't forget to break; or return!
Makes handling I/O streams and similar things easier
Gets rid of a lot of finally blocks
Pluggable due to new interface: AutoCloseable
InputStream is = null;
BufferedInputStream bs = null;
JsonReader json = null;
try {
is = new FileInputStream("my-file.json");
bs = new BufferedInputStream(is);
json = new JsonReader(bs);
//Do your stuff
} catch (IOException ex) {
//handle it
} finally {
try {
if (json != null)
json.close();
if (bs != null)
bs.close();
if (is != null)
is.close();
} catch (IOException ex) {
//Handle this exception
}
}
try (
InputStream is = new FileInputStream("my-file.json");
BufferedInputStream bs = new BufferedInputStream(is);
JsonReader json = new JsonReader(bs)
) {
//Do your stuff
} catch (IOException ex) {
//handle it
}
public class MyResource implements AutoCloseable {
public void doSomethingResourceful() {
}
@Overrides
public void close() {
//close me
}
}
try (MyResource mr = new MyResource()) {
mr.doSomethingResourceful();
}
Simplifies complicated try-catch blocks
Assume that jsonReader.read() throws a JsonException
try (
InputStream is = new FileInputStream("my-file.json");
BufferedInputStream bs = new BufferedInputStream(is);
JsonReader json = new JsonReader(bs)
) {
json.read();
} catch (IOException ex) {
LOG.error("Error reading json", ex);
} catch (JSONException ex) {
LOG.error("Error reading json", ex);
}
We could catch Exception, but what if there's some other exception that we want to let go?
try (
InputStream is = new FileInputStream("my-file.json");
BufferedInputStream bs = new BufferedInputStream(is);
JsonReader json = new JsonReader(bs)
) {
json.read();
} catch (SomeOtherException ex) {
throw ex; //Propogate it up
} catch (Exception ex) {
LOG.error("Error reading json", ex);
}
But what about runtime exceptions we don't know about?
Solution
try (
InputStream is = new FileInputStream("my-file.json");
BufferedInputStream bs = new BufferedInputStream(is);
JsonReader json = new JsonReader(bs)
) {
json.read();
} catch (IOException | JSONException ex) {
LOG.error("Error reading json", ex);
}
Simplifies creating generic objects
//Old, verbose way
Map<String, String> java6 = new HashMap<String, String>();
//New, compact way
Map<String, String> java7 = new HashMap<>();
Most of the big changes in Java 8 exist to make one thing possible: the Streams API
We're going to talk about Lambdas first, though.