Passing array as a parameter to a method:
- We can address of array as a parameter to method.
- Using the address, we can process elements of that array.
class Main
{
public static void main(String[] args)
{
int arr[ ] = {10,20,30,40,50};
Main.display(arr);
}
static void display(int list[])
{
System.out.println("Array elements are : ");
for (int i=0 ; i<list.length ; i++)
{
System.out.println(list[i]);
}
}
}
- Passing array is nothing but passing memory address of block.
- Using the address, we can process elements are array.
- Duplicate array will not be created. Just address will be shared.
class Main
{
public static void main(String[] args)
{
int arr[ ] = {10,20,30,40,50};
Main.modify(arr);
System.out.println("Array elements are : ");
for (int i=0 ; i<arr.length ; i++)
{
System.out.println(arr[i]);
}
}
static void modify(int list[])
{
for (int i=0 ; i<list.length ; i++)
{
list[i] = list[i] + 5;
}
}
}
Method returns array:
- A method can take array as an input and can return the array as output.
- Return type should be an array in the prototype of function
class Main
{
public static void main(String[] args)
{
int x[ ] = Main.test();
System.out.println("Array elements are : ");
for (int i=0 ; i<x.length ; i++)
{
System.out.println(x[i]);
}
}
static int[] test()
{
int arr[ ] = {10,20,30,40,50};
return arr;
}
}