We’ll rearrange your code:
public class Teste {
public static int[] vetorFuncao() {
int[] numerosAleatorios = new int[10];
for (int i = 0; i < 10; i++) {
numerosAleatorios[i] = ((int) (Math.random() * 10)) + 1;
}
return numerosAleatorios;
}
public static void main(String[] args) {
int[] vetor = vetorFuncao();
}
}
First, pay attention to new
. This keyword says something will be created. When you make a new int[10]
you are creating an array with 10 positions. The part of the numerosAleatorios =
says that this array will be assigned to the variable numerosAleatorios
, who’s kind int[]
. So the line int[] numerosAleatorios = new int[10];
does that:
- Declares a type variable
int[]
calling for numerosAleatorios
.
- Creates an integer array of 10 positions.
- Assigns this newly created array to the variable
numerosAleatorios
.
Further down, still within the method vetorFuncao()
you have the return numerosAleatorios;
. This statement returns the array numerosAleatorios
as a result of the method that called.
Within the method main(String[])
, when you call vetorFuncao()
, you are invoking the method vetorFuncao()
. The method vetorFuncao()
will return the array it created as a result. When you have the int[] vetor = vetorFuncao();
, this array that is created within vetorFuncao()
will be assigned to the variable vetor
. The main
will not create by itself any array, it will only receive the array that vetorFuncao()
took charge of creating.
In this case, the main
is relying on the method vetorFuncao()
the creation of the array, including its size. Inside the vetorFuncao()
, the size is set to 10, and it is this array that will be returned. If you want to set the size on main
, just use a parameter:
public class Teste {
public static int[] vetorFuncao(int tamanho) {
int[] numerosAleatorios = new int[tamanho];
for (int i = 0; i < tamanho; i++) {
numerosAleatorios[i] = ((int) (Math.random() * 10)) + 1;
}
return numerosAleatorios;
}
public static void main(String[] args) {
int[] vetor = vetorFuncao(10);
}
}
In this case, the method vetorFuncao
"asks" who will use it the size of the array that will be created, and this size is directly passed to new
. The main
reports this value as 10 in the vetorFuncao
.
Thank you very much!
– Rapha085