0

I'm trying to grab a random value from this array. When I run the program it just prints 0 for x. Why isn't it printing the updated value that is returned from the function?

import java.util.*;
public class randomArray
{
    public static void main(String[] args)
    {
        int[] myArray = new int[]{1,2,3};
        int x = 0;
        getRandom(myArray, x);
        System.out.println(x);
    }
    public static int getRandom(int[] array, int h) 
    {
        int rnd = new Random().nextInt(array.length);
        return h;   
    }
}
Freezy
  • 1
  • 2

3 Answers3

1

You need to change your getRandom() to the following

public static int getRandom(int[] array) 
{
    int rnd = new Random().nextInt(array.length); //generate random index
    return array[rnd]; // get element by random index
}

And then call System.out.println(getRandom(myArray));

Ivan
  • 8,508
  • 2
  • 19
  • 30
  • Thank you! That was a very fast response. So calling methods to a print statement just prints the thing that is returned to main? – Freezy Aug 31 '18 at 23:22
  • Correct. Executing `System.out.println();` will print value returned from that method. – Ivan Aug 31 '18 at 23:24
1

Java passes the parameters by value, not by reference, so the x value is not updated inside the getRandom method. So when you call getRandom, the h variable is created and gets a copy of the value of the parameter x, that is the 0 value. Then you are returning the value of h that has a 0 value.

0

Java is "pass-by-value" for primitive types. That means when you pass a number as an argument to another method, the original value will not be modified inside that method. You expect that x variable becomes h variable, but these are two different variables and updating h will not update 'x'.

Krystian G
  • 2,842
  • 3
  • 11
  • 25