In java, a Void that makes a sum, returns value?

2

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);
}
    
asked by anonymous 04.10.2017 / 20:31

1 answer

8
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

  • The return type is void , that is, the method does not return value
  • The method name is sum
  • The arguments he can receive are two integers, 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
    
        
    04.10.2017 / 20:38