In java, a Void that sums, returns value?

Asked

Viewed 461 times

2

My doubt is about what exactly is a java return. Because I think the sum answer would be a kind of return, this is correct?

void soma (int a, int b) {
     int s = a + b;
     System.out.println (s);
}
  • 3

    void in Signature means no return.

  • 2

    Void does not return value, could explain your doubt better?

  • in the algorithm you wrote it just writes the value, and does not return since it is a void method.

  • Do you want a way to return the value even if it is void, or are you not understanding why the value is not being returned?

  • Okay, so my question is what exactly is a java return. Because I think the answer to the sum would be a kind of return. Forgive my ignorance.

  • The return is something that you can take advantage of, in other words, all the processing is done and in the function call only takes the part that matters. Printing on the console is not a return. For example int total = soma(10, 5); if(total > 7){ System.out.println ("aprovado");}else{ System.out.println ("exame");}. The return of the function that has been assigned to total was used for something a decision in the case.

  • Oh yes, very obg guy. Perfect bro. Thanks for the clarification.

  • In short, for a return to occur it is necessary return, so your method has no return, then there is no return.

Show 3 more comments

1 answer

9

void soma (int a, int b) {
     int s = a + b;
     System.out.println (s);
}

That up there is a method, which is a kind of function or subroutine. The first line says that

  1. The type of return is void, i.e., the method does not return value
  2. The method name is sum
  3. The arguments he can receive are two integers, a and b.

The result of the sum is not a return, it is only 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 is going to return this value, it would need to have a different signature, stating that it returns an integer:

int soma (int a, int b) {
     return a + b;
}

Notice now he says he returns one int, and in fact does so through the keyword return. If the method has no Return, it necessarily is of the type void. If you have return, the signature must indicate the type of the 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
  • 1

    Great, very enlightening. Thank you very much.

  • 2

    And it is also clear that a method void may have a return as long as it has no value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.