With regard to methods [closed]

-1

Why are the methods with return of values (return) and empty methods (void) useful? What is the utility of each one?

    
asked by Nefasto 24.05.2017 в 09:07
source

1 answer

3

This should look at Oracle documentation , but I'm going to make a brief summary.

The void methods do not return anything, that is, they do actions inside, or modify values or alter the operation of the program, but they do not return values or anything. that is:

private void suma(){
  int x=1;
  int i=2;
  int z= x + i;
}

This function makes a sum that will not come out of this method (This method has no use, it is just an example). On the other hand, if we want a value to be returned to us, we would do something like this:

private int suma(){
      int x=1;
  int i=2;
  int z= x + i;
  return z;
}

In this way, from outside we could get z as follows:

public static void main(String [] args)
{
    int suma = suma();//Suma será 3
 }

In short, if you want to get any type of value from a function, you must return a value. A possible utility is to compare two values:

private boolean sonIguales(int i, int j){
   boolean b=false;
   if(i==j){


      b=true;
}
return b;
}

public static void main(String [] args)
{
    if(sonIguales(1,1)){
     //hacer cosas
   }
 }
    
answered by 24.05.2017 в 09:26