-1

Why does this code work

void hello()
{
hello();
return;
}

while this does not

void hello(){return hello();}

Error:

java.java:13: error: incompatible types: unexpected return value
return hello();

(Please ignore the logical error)

The main question: Why cannot we return void to a void function?

Does Java by any means provide support another type of void, maybe a wrapper class called Void?

Mohit Shetty
  • 1,551
  • 8
  • 26

5 Answers5

1

he main question: Why cannot we return void to a void function?

Because void function does not return a value thus you cannot return anything. In void method context return; is just "finish method execution" or "quit method", not "return nothing";

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
1

As for one-liners, try this:

void hello() { hello(); }

istead of

void hello() { return hello(); }
Usagi Miyamoto
  • 6,196
  • 1
  • 19
  • 33
  • Sorry for being unclear the main function would be an conditional return and there would be other statements ahead. – Mohit Shetty Apr 03 '20 at 14:44
1

There is a way

class A {
  Void a() {
    // ...
    return a();
  }
}

but java.lang.Void is an uninstantiable representation of the void type meaning you can't make instances out of it (and, sensibly, you aren't supposed to). Eventually, you would need to return a value, it could be a null - the only "legit" one I can think of.

It has applications with generics and the Reflection API, but I doubt it being used here for the purpose of making a recursive method fancier (?).

class A {
  Consumer<String> a() {
    return System.out::println;
  }
}

You might want to return an instance of a function that returns void. Then, a functional interface java.util.function.Consumer might be a good fit.

Actually, it could be any interface of the kind that would suit you best. For instance,

class A {
  Runnable a() {
    // ...
    return () -> a();
  }
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
1

With return type void, you can not return anything but with return type, Void, you can return null e.g.

public class Main {
    public static void main(String[] args) {
        hello();
    }

    static Void hello() {
        System.out.println("Hello");
        return null;
    }
}

Output:

Hello

You can find some more uses of Void at https://www.baeldung.com/java-void-type

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

Because when a method's return value is void it does not accept any parameter, even void itself.

return x; indicates that control is leaving the method and that its result is the value of x.

return; indicates that control is leaving the method without a result.

This code does not work so I guess you should not expect yours to work too.

void fun () {return void;} // does not work

Please refer to this answer.

Baraa
  • 1,476
  • 1
  • 16
  • 19