Search code examples
javamethodsreturn

Java: void method returns values?


So, I think I misunderstood something about how method returns values. I don't understand why list[0] is 3 in the output since that is a void method, which doesn't return anything back to main method... If the void method could actually return the value, then why num would still be 0..... wouldn't num become 3 as well?? Or void method doesn't return any values, except arrays?

public static void main (String []args){

    int []list = {1,2,3,4,5};
    int number = 0;

    modify(number, list);

    System.out.println("number is: "+number);

    for (int i = 0; i < list.length; i++)
    {
        System.out.print(list[i]+" ");
    }

    System.out.println();
}
public static void modify (int num, int []list){

    num = 3;
    list[0] = 3;
}

Output:

number is: 0

3 2 3 4 5 

Solution

  • You likely need to familiarize your self with concepts of "pass by value", "pass by reference", and the understanding that objects are references (passed by value between method calls).

    "number" is a simple integer - passed by value to the modify method. So even if the value assigned to "num" changes within the method, the original variable used by the caller of this method remains the same.

    "list" is also passed by value, but "list" is an object, so you are passing the reference to this object (by value) to the modify method. So if you change the internals of an object within a method, you are changing the same object referenced by the caller.

    Now if you did this:

    public static void modify (int num, int [] list)
    {
    
        num = 3;
        int [] newlist = {9,8,7,6,5,4};
        list = newlist;
        newlist[0] = 3;
    }
    

    Then the "list" that was passed into modify never gets modified because "list" within the modify method gets changed to point to a different object altogether.