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

COMPUTER SOFTWARE APPLICATION - CITS




           Explanation:
           •  In this program, we have a class StringConcatenator with two overloaded methods named concatenate.

           •  The first method concatenates two strings.
           •  The second method concatenates three strings.
           •  In the main method, we call each of the overloaded methods to concatenate strings with different numbers of
              parameters.
           These examples illustrate how overloaded methods allow us to create methods with the same name but
           different behaviors based on the parameters passed to them. It enhances code readability and reusability by
           providing multiple ways to accomplish a task.


           TASK 3: Summing Numbers
           // Summing Numbers  using Overloaded Methods

           public class SumCalculator {
           // Method to sum two integers
           public static int sum(int a, int b) {
           return a + b;

           }
           // Method to sum three integers
           public static int sum(int a, int b, int c) {
           return a + b + c;
           }
           // Method to sum an array of integers

           public static int sum(int[] numbers) {
           int total = 0;
           for (int num : numbers) {
           total += num;

           }
           return total;
           }
           public static void main(String[] args) {
           int num1 = 5;

           int num2 = 10;
           int num3 = 15;
           int[] array = {3, 6, 9, 12};
           // Calculate sums using overloaded methods
           System.out.println(“Sum of two numbers: “ + sum(num1, num2));

           System.out.println(“Sum of three numbers: “ + sum(num1, num2, num3));
           System.out.println(“Sum of array elements: “ + sum(array));
           }
           }



                                                           124

                               CITS : IT & ITES - Computer Software Application - Exercise 98
   134   135   136   137   138   139   140   141   142   143   144