In Java, arrays are reference types, meaning that when you pass an array to a method, the method receives a reference to the array. This means that if the method modifies the array (e.g., by changing the value of an element), the modifications will be visible outside the method. In other words, Java does not make a copy of the array when you pass it to a method, which is what would happen if arrays were value types.
One-Dimensional Arrays:
Here is an example of passing a one-dimensional array to a function:
class Main
{
public static void main(String[] args)
{
int[] array1D = { 1, 2, 3, 4, 5 };
printArray(array1D);
}
static void printArray(int[] array)
{
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
}
}
In this example, `array1D` is a one-dimensional array. This array is passed to the `printArray` method which prints all elements of the array.
Two-Dimensional Arrays:
For two-dimensional arrays, it's pretty similar:
class Main
{
public static void main(String[] args)
{
int[][] array2D = { {1, 2, 3}, {4, 5, 6} };
printArray(array2D);
}
static void printArray(int[][] array)
{
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
System.out.println(array[i][j]);
}
}
}
}
In this example, `array2D` is a two-dimensional array. This array is passed to the `printArray` method which prints all elements of the array.