Very briefly capturing some of new/ update in API that were introduced after Java 8 that may come handy for dev folks while programming

Overview

Beyond Java 8

Very briefly capturing some of new/ update in API that were introduced after Java 8 that may come handy for dev folks while programming. Also have created tests demonstrating those APIs and playaround with it.

Table of content

Java 9

1. Factory method for collections

A convenient factory method is introduced in the different collections class like Map, List, set that let us create immutable collection object with ease.

Map:

Map myMap = Map.of("K1", "Some val for K",
                "G1", "Some val for G1");

By above method you can add atmost 10 entries. To create a immutable map with more than 10 entries, the below method can be used.

import static java.util.Map.entry;
import static java.util.Map.ofEntries;

Map bigMap = ofEntries(
        entry("one","asd"),
        entry("two","asd"),
        entry("three","asd"),
        entry("four","asd"),
        entry("five","asd"),
        entry("six","asd"),
        entry("seven","asd"),
        entry("eight","asd"),
        entry("nine","asd"),
        entry("ten","asd"),
        entry("eleven","asd")
        ); 

Similarly, List and set to have these factory methods as below.

List:

List mylist = List.of("Debian", "George", "cloney");

Set:

Set mylist = Set.of("Debian", "George", "cloney");

Note:

  1. Returns an immutable object.(ie) you can't add or remove element.
  2. Does not accept null as argument.
  3. Set throws exception on duplicate value.

2. Improvement in Try catch with resource

From java 9, we dont have to necesarly declare the resource variable inside the try with resource block. any reference of Final closable reference can be passed as below.

 MockClosableResource closableResource = new MockClosableResource();
 try (closableResource) {

 } catch (IOException e) {
    e.printStackTrace();
 }
 Assertions.assertTrue(closableResource.isClosed);

Key point:

  • The resource variable should be final or effectively final
  • if wish to pass mutiple varaible seperate them by ;

Java 10:

1. Type inference with var

Var keyword allow local varaible type inference. For Example

var myMap = new HashMap<String, String>();

Note:

  • Can only be used for local varaible.
  • Once declared can't override the type. Else will result in compilation error. For example,
var someNum = 10;
someNum = "asda"; // Compilation error
  • the value for var variable should be assigned during declaration itself. You cant do something like below.
var someText;
someText = ""; //Compilation error

Java 14:

1. Switch expression

In java 13, the verbose switch statement is replaced with enhanced switch experession

private void printHeroDescription(String name) {
        switch (name) {
            case "Supes":
                System.out.println("Man of steel");
                break;
            case "Batsy":
                System.out.println("A great detective");
                break;
            case "WonderWoman":
                System.out.println("Demi goddes");
                break;
            case "Flash":
            case "QuickSilver":
                System.out.println("Run fast");
                break;
            default:
                System.out.println(name);
                break;
        }
    }

The above code can be replaced with below

System.out.println("Man of steel"); case "Batsy" -> System.out.println("A great detective"); case "WonderWoman" -> System.out.println("Demi goddess"); case "Flash", "QuickSilver" -> System.out.println("Run fast"); default -> System.out.println(name); } } ">
private void printHeroDescription(String name) {
    switch(name) {
            case "Supes" -> System.out.println("Man of steel");
            case "Batsy" -> System.out.println("A great detective");
            case "WonderWoman" -> System.out.println("Demi goddess");
            case "Flash", "QuickSilver" -> System.out.println("Run fast");
            default -> System.out.println(name);
        }
}        
  • Switch has a fallback mechanism in which the control flow continues to next case until it encounter a break statement. Though it is not evil by itself , it causes a lot of problem if not careful.
  • switch expression eliminates the need for break statement.
  • Two or more case with similar body can be combined in single case expression (eg: flash and quick silver)
  • If the case body have more than one line, it can be wrapped in curly braces.
  • The switch expression can be extended even more. It can return a value. For example the above method can be rewritten as below
"Man of steel"; case "Batsy" -> "A great detective"; case "WonderWoman" -> "Demi goddess"; case "Flash", "QuickSilver" -> "Runs fast"; default -> "Not available right now"; }; System.out.println(heroDesc); }">
private void printHeroDescription(String name) {
        String heroDesc = switch (name) {
            case "Supes" -> "Man of steel";
            case "Batsy" -> "A great detective";
            case "WonderWoman" -> "Demi goddess";
            case "Flash", "QuickSilver" -> "Runs fast";
            default -> "Not available right now";
        };
        System.out.println(heroDesc);
    }
  • However, while doing as above, what if the case body is more than one line. Somehow we need to indicate a value need to be returned. The return cannot be used as it might create ambuguity in case we are returning the switch expression itself in the method. Instead yield is used.
  • Also in case of using an enum as the selector for switch case and if we define case for all possible of enum, then we dont need to provide default case!!!
  • IDE can help a lot in converting existing switch to enhanced switch expression.

Java 15:

1. Text block

Text block were introduced in order to declare string that span multiple line. The Text block can be created by putting string under thriple quates as below.

   String bigBlockWithNewLine = """
                You're not brave... "men are brave".
                You say that you want to help people, but you can't feel their pain... their mortality...
                It's time you learn what it means to be a man.
                """;

Key things:

  • Text block is again a string instance.
  • The goal of text block is to enable us to declare string with multiple line with minimal escape squeance and improve code readability.
  • The trailing space in each line is removed automatically. If wish to preserve it use \s
  • To prevent the text going to new line then use \
    String bigBlockWithNewLine = """
                I'm older now than my father ever was. \
                This may be the only thing I do that matters\
                """;
    var expected = "I'm older now than my father ever was. This may be the only thing I do that matters";
    assertEquals(expected, bigBlockWithNewLine);
  • String interpolation is not supported in text block as of now.

Java 16:

1. Pattern matching with instance of

An enhancement brought to get rid of instanceof-and cast idiom that we usually do in java like below.

    void hadleVal(Obj someVal){
        if(someVal instanceof String) {
            String s = (String) someVal;
            //Do some stuff...
        }
    }   

Instead, we can do something like below.

void hadleVal(Obj someVal){
        if(someVal instanceof String s) {
            //Do some stuff with variable s...
        }
    }   

Here when the predicate someVal instanceof String passes, then it also converts the someVal variable to String and store it in s

Key point:

  • You can chain your condition to do something like this.
    if(someVal instanceof String s && s.length()>5) {
    
     }
  • But you can't do OR condition as below. Because the resultant variable will be accessible only if the predicate get pass.
    if(someVal instanceof String s || s.length()>5) { //Compilation error
    
     }
You might also like...

Allows changing of hurt animation modifier, changing how much the user's camera moves after the player being hurt.

Hurt Animation Modifier Allows changing of hurt animation modifier, changing how much the user's camera moves after the player being hurt. Credit to W

May 17, 2022

fork of autoGG for fabric to pay respect to Techno after games.

AutoTechno Description: This mod is a tribute to the youtuber Technoblade and to their family which takes on a new spin to the usual auto gg mods by i

Jul 23, 2022

Repositório destinado para projeto da semana Spring React do Dev superior. Utilizando Java, TypeScript e Frameworks

Repositório destinado para projeto da semana Spring React do Dev superior. Utilizando Java, TypeScript e Frameworks

⚛️ DS Meta - Semana Spring-React Repositório destinado para projeto da semana Spring React do Dev superior. Utilizando Java, JavaScript e Frameworks.

Sep 11, 2022

Android PackageInstaller API silent update test app

Android PackageInstaller API silent update test app

Dec 13, 2022

Projeto criado na semana Spring React organizado pela escola Dev Superior com foco na prática/aprendizado das tecnologias Spring e React.

DSVendas Projeto criado na semana Spring React organizado pela escola Dev Superior com foco na prática/aprendizado das tecnologias Spring e React. htt

May 18, 2021

Mc-msa-token-getter - Scripts to retrieve MC authentication tokens for use in modding dev envs.

Minecraft MSA Token Getter Python and Java scripts to retrieve MC authentication tokens for use in modding dev envs. Requires a properly configured Az

Jan 3, 2022

Sportheca Mobile DEV Week - Simulador de Partidas 🎲

Sportheca Mobile DEV Week - Simulador de Partidas 🎲

Sportheca Mobile DEV Week - Simulador de Partidas 🎲 Projeto desenvolvido no bootcamp Sportheca da DIO. Desenvolvimento Mobile Nativo Para Android Obj

Aug 5, 2022

A neo4j procedure for tabby (dev)

tabby-path-finder #0 简介 A neo4j procedure for tabby tabby污点分析扩展,用于根据tabby生成的代码属性图做动态剪枝+深度搜索符合条件的利用链/漏洞链路。 #1 用法 生成jar文件 mvn clean package -DskipTests

Dec 11, 2022

Projeto criado no Santander Dev Week 2022 + DIO com o intuito de desenvolver uma camada de APIs (backend) que será utilizada pelo frontend.

Santader Dev Week + DIO 2022 - APIs Backend da aplicação de movimentação financeira Este repositório contém o backend da aplicação que foi desenvolvid

Sep 7, 2022
Owner
Jayaramanan Kumar
A passionate developer who loves fiddling around with Web/mobile technology stack.
Jayaramanan Kumar
For Jack language. Most of codes were commented with their usage, which can be useful for beginner to realize the running principle of a compiler for object-oriented programming language.

Instructions: Download the Java source codes Store these codes into a local folder and open this folder Click the right key of mouse and click ‘Open i

gooooooood 1.1k Jan 5, 2023
this repo is probs gonna die cuz idk very much java but i will update it when i learn how to actually DO SHIT

pastegod.cc shitty rename of zihasz client base rn but as i learn java i will paste-i mean add modules ;) (23/9/2021) why is everyone starring and wat

null 9 Dec 9, 2022
Original FishHack from the very beginning of 2020 (WARNING: VERY BAD CODE)

FishHack Original FishHack from the very beginning of 2020 (when I did not know what was I doing) Credits to BleachHack for my first ever coding knowl

null 3 Dec 2, 2022
Creazione di una classe che si occupi della gestione di dipendenti e utilizza interfaccia grafica.Problema : come utilizzo l'ArrayList comune per tutte le classi?

Dipendenti Creazione di una classe che si occupi della gestione di dipendenti e utilizza interfaccia grafica.Problema : come utilizzo l'ArrayList comu

null 2 Apr 23, 2022
This is some Discord bot I made to help me learn Java. Not very useful yet.

JennyChan This is some Discord bot I made to help me learn Java. Not very useful yet. What it can do so far: Reply to mention List commands Show bot u

null 0 Sep 1, 2022
Very spicy additions to the Java programming language.

Project Lombok Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another g

Project Lombok 11.7k Dec 30, 2022
An evil RMI server that can launch an arbitrary command. May be useful for CVE-2021-44228

evil-rmi-server An evil RMI server that can launch an arbitrary command. May be useful for CVE-2021-44228 in a local privesc scenario Build ./gradlew

Adam Bertrand 12 Nov 9, 2022
MessageEngine by afkvido. Alpha test is the most updated but may contain many bugs

MessageEngine Alpha Alpha Testing This is the most frequently updated, fresh, and potentially most glitchy version of MessageEngine. This version will

gemsvidø 3 Feb 7, 2022
Render After Effects animations natively on Android and iOS, Web, and React Native

Lottie for Android, iOS, React Native, Web, and Windows Lottie is a mobile library for Android and iOS that parses Adobe After Effects animations expo

Airbnb 33.5k Jan 3, 2023
Kyrestia, named after Kyrestia the Firstborne, is a process engine supporting mainstream process definition standards.

Kyrestia Kyrestia, named after Kyrestia the Firstborne, is a process engine supporting mainstream process definition standards. It is not only lightwe

Weiran Wu 32 Feb 22, 2022