Void in Java

Void in Java

Purpose:

represent the void return type as a class and contain a Class public value. It is not instantiable as the only constructor is private. The only value for Void is null.

Type Match:


Class<PrintStream> printStreamClass = PrintStream.class;
Method method = printStreamClass.getDeclaredMethod("println", String.class);
boolean equals1 = method.getReturnType().equals(void.class);
boolean equals2 = method.getReturnType().equals(Void.TYPE);
System.out.println("equals void class " + equals1);
System.out.println("equals Void TYPE " + equals2);
`

Generics Usage


Callable<Void> callable = new Callable<Void>() {
    @Override
    public Void call() {
        System.out.println("Hello!");
        return null;
    }
};

Attention: null should be returned.

Avoid Using It

By passing a Runnable Object, which implements a void run method.


public static <T> void defer(Runnable runnable) {
    runnable.run();
}

public static void main(String[] args) throws NoSuchMethodException {

    Runnable runnable = () -> System.out.println("Hello!");
    defer(runnable);
}

Reference

[1]. https://www.baeldung.com/java-void-type