1

I'm learning Java, and from what I learned, is that you need to specify the value that a function return.. If it doesn't return a value than it is void.. However in the below program, I'm able to change the values of an array from a void function. Can anybody explain this to me please?

 public class ArraysInMethods {
    public static void main(String args[]){
        int rd[] = {2,3,4,5,6};
        change(rd);

        for(int y: rd){
            System.out.println(y);
        }

    }

    public static void change(int x[]){
        for(int counter = 0; counter<x.length;counter++){
            x[counter]+=5;
        }
    }

}
JDOE
  • 25
  • 6

1 Answers1

3

I'm learning Java, and from what I learned, is that you need to specify the value that a function return.

That is correct only for methods returning values, i.e. methods other than void. These methods define expressions, while void methods define statements.

Calling your change method is a statement, in the sense that it lacks return values. It does not mean, however, that it cannot change the state of your running program - for example, give different values to variables.

However in the below program, I'm able to change the values of an array from a void function.

You are not returning a value from your void function; all you do is modifying the array in place. This is allowed, because arrays are passed by reference.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523