Page 114 - CTS - CSA TP - Volume 2
P. 114

COMPUTER SOFTWARE APPLICATION - CITS




           3  Passing Arrays to Methods
           TASK 1: to pass data and objects to methods in Java programs
              public class ArrayDemo {

                  public static void main(String[] args) {
                      int[] numbers = {1, 2, 3, 4, 5};


                      // Passing an array to a method

                      printArray(numbers);
                  }
                  // Method to print array elements
                  public static void printArray(int[] arr) {
                      System.out.println(“Array elements:”);

                      for (int num : arr) {
                          System.out.print(num + “ “);
                      }
                  }
              }

           Output:
















           Explanation:

           •  In this program, we define an array numbers containing integers.
           •  We define a method printArray that takes an array of integers as a parameter and prints its elements.
           •  In the main method, we call the printArray method and pass the numbers array as an argument.
           These examples demonstrate how to pass data and objects to methods in Java programs. It’s important to note
           that Java is pass-by-value, meaning that when you pass a parameter to a method, a copy of the parameter’s
           value is passed, not the actual object itself. For objects, the value passed is the reference to the object in memory.
           Thus, changes made to parameters inside the method are reflected in the original objects or variables if they are
           mutable.
















                                                           99
                                CITS : IT & ITES - Computer Software Application - Exercise 95
   109   110   111   112   113   114   115   116   117   118   119