My question is what exactly is a return in java. For I think the sum answer would be a kind of return, is that correct?
void soma (int a, int b) {
int s = a + b;
System.out.println (s);
}
My question is what exactly is a return in java. For I think the sum answer would be a kind of return, is that correct?
void soma (int a, int b) {
int s = a + b;
System.out.println (s);
}
void soma (int a, int b) {
int s = a + b;
System.out.println (s);
}
This above is a method, which is a function type or subroutine. The first line says
void
, that is, the method does not return value a
and b
. The result of the sum is not a return, it is just the result of the sum :) It can, for example, be printed on the screen from within the method itself, as you did. If the method returns this value, it would need to have a different signature, specifying that it returns an integer:
int soma (int a, int b) {
return a + b;
}
Note that it now says that it returns a int
, and in fact does so using the return
keyword. If the method has no return, it is necessarily void
. If it has return
, the signature must indicate the type of value that will be returned. And this return is always a return to the caller. For example:
int resultado = meuObj.soma(2, 3); // variável resultado receberá valor 5