I wanted to ask if I was currently reading Java literature, but I still didn’t understand why void returns nothing.

For example:

public void firstMethod(){ System.out.println("Hello!"); } 

In fact, the word "Hello" is returned to us as I understand it.

But I scored the code in Intellij idea:

 public void run(){ return 10; } 

The idea began to swear, they say change to public int run() .

Not really understood (void returning nothing), please explain.

    3 answers 3

    The function must return some kind of structure when it is called (or return nothing). void is a specifier that indicates that the function should not return anything. It is important to note that return is understood as return {...}, and not the operation of the function itself. Those. if you have functions of the form int Method (), then return must be present in the function itself.

    Void does not assume such a return. However, the return can be used for early termination of the function.

    • If more about the return. In your case, the firstMethod () call in the main method will not return anything. But if the function were int firstMethod () and there was a return 0; return in it, then the call int a = firstMethod () would put the value a in the variable a 0. - Khetag Abramov

    This means that no variable values ​​are returned. Accordingly, the type of the return value is not specified and written void.

      When you call a method in code, imagine in your mind instead what you want to get from it. What is happening in the body of the method at this time does not interest us: there may be something printed on the console, some objects may be created, other methods may even be called or all at once. The main thing is that he must return to his place when called. Take a look at this example:

       public static **int** sum(int a, int b) { return a + b; } int sumResult = sum(15, 23); 

      And this:

       public static **void** sumAndPrint(int a, int b) { System.out.println(a + b); } 

      We can use the first method in order, by calling it, to immediately write the result into some kind of variable. The second method returns nothing and can be used ... well, just to look at the result in the console.