+ 2
What is a void in this case?
class MyClass { static int sum(int val1, int val2) { return val1 + val2; } public static void main(String[ ] args) { int x = sum(2, 5); System.out.println(x); } } // Outputs "7" When you do not need to return any value from your method, use the keyword void. Notice the void keyword in the definition of the main method - this means that main does not return anything. However, in this example, isn't there an output; which is 7? In this case I do not understand what the "void" is for.
7 Respostas
+ 8
The void keyword specifies that nothing gets returned from the function.
Remember that output to the console != returning a value. Returning a value is essentially passing a value from the function back to where it is called.
The main function (of type void) does not return a value to elsewhere. It simply outputs the value, and terminates it's execution. On the other hand, we can see that the sum() function returns a value to main.
+ 1
You should clearly recgonize the
output and the return-value.
The output is what you can see
while running the program.
The return-value is not what you
can see,but you can assign it to
some varibles.
Here,the function gives output,but
it has no return-value(because the
return keyword is not contained).
And the void keyword is just for
this type of function which has no
return-value(no return keyword contained),but it might have output.So the void here is for the
same using,as usual.
+ 1
void doesn't return the value
+ 1
Your main() class doesn't have a return value and that is different from an output value. Your MyClass() class does have a return value and it wouldn't be void. It's all about placement and intent.
+ 1
Like Hatsy Rei already said output is not returning a value!
If your boss asks "can you add two numbers and give me the result" he/she wants a number as an answer. It is like your sum function where the caller wants an int to be returned no matter what the function else is doing.
If your boss says "do something and tell someone else but not me" your boss wants no result. It is like your main function returning nothing (void).
A function can return void or only a single value of one type like int. But within a function you can output as much as you want, even different things.
So output (tell someone else) is not returning (feedback to the caller).
0
The void means that there is no return. For Java, the main method will always have a void. By default, methods have a return option unless they are void methods.
Public- This method is public and accessible to any calls
Static- This means there is only one
Void- No return call.
Main- The "starting" main method line of a program. All the code starts below here
String[]- This is for an array.
Args- This is for arguments
0
Void is used when you are not required to return anything in a method..