Java program to pass arraylist as the function argument

Here's a Java program that demonstrates how to pass an ArrayList as a function argument:

refer t‮igi:o‬ftidea.com
import java.util.ArrayList;

public class ArrayListExample {

    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<Integer>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);
        System.out.println("Original list: " + numbers);
        incrementList(numbers);
        System.out.println("List after incrementing: " + numbers);
    }
    
    public static void incrementList(ArrayList<Integer> list) {
        for (int i = 0; i < list.size(); i++) {
            int n = list.get(i);
            list.set(i, n + 1);
        }
    }
}

Explanation:

The main method creates an ArrayList of integers and adds five values to it. It then prints the original list to the console.

The incrementList method takes an ArrayList of integers as input and increments each element of the list by one. It uses a loop to iterate over the list, getting each element using the get method and setting the element back into the list using the set method with its value incremented.

The main method calls the incrementList method, passing the original ArrayList as an argument. After the method returns, the main method prints the modified list to the console.

Note that ArrayList is a reference type, which means that when you pass an ArrayList to a method, you are actually passing a reference to the object, not a copy of the object itself. As a result, any changes made to the ArrayList inside the method will be reflected in the original ArrayList outside the method.