Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web

More Java 8 Goodies

0.00/5 (No votes)
30 Jun 2015CPOL 4.4K  
More Java 8 goodies

I did streams yesterday but let's touch on a couple fun points. Again, I am a little late to the party on this stuff but I doubt I am the only one.

Optional

Could this be the end of null pointer exceptions? This is a lot nicer way to default values and do null checks. If you follow my blog, you know I hate ternary operators due to their poor readability and this does away with that in case of default values.

Java
Optional<String> displayText = Optional.ofNullable(null);
System.out.println(
    "display text found? " + displayText.isPresent() );
System.out.println(
    "display text: " + displayText.orElseGet( () -> "n/a" ) );
System.out.println(
    displayText.map( text -> text.toUpperCase() ).orElse(" ") );

Interface Changes

I am not entirely sure about this one because the line between abstract class and interface is really blurry.

Default Methods

This can help with backwards compatibility when adding new methods to interfaces.

Java
public interface MouseTrap {
    // ...
    default void setTrap() {
       // ...
    }
 }

Static Methods

Java
private interface MouseTrapFactory {
    // Interfaces now allow static methods
    static MouseTrap createMouseTrap(String bait) {
    return new BetterMouseTrap(bait);
}

Native JavaScript Support

Since I haven't used it really yet, I don't want to just copy other peoples examples but now with Java 8 the native JavaScript engine that can be accessed with in is Nashorn (pr. "nass-horn"). The JavaScript you write can be executed from the command line (which can even call Java classes) or within Java classes.

Related Content

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)