Develop minimum 4 program based on variation in methods i.e. passing by value, passing by reference, returning values and returning objects from methods.

Here are four Java programs based on different variations of methods:

1. Passing by Value

In this example, we have a method that accepts two integer arguments and swaps their values using a temporary variable.

Create a Example1.java file and write this code in it.

public class Example1 {
    public static void swap(int a, int b) {
        int temp = a;
        a = b;
        b = temp;
        System.out.println("Inside swap method: a = " + a + ", b = " + b);
    }

    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        System.out.println("Before swap: x = " + x + ", y = " + y);
        swap(x, y);
        System.out.println("After swap: x = " + x + ", y = " + y);
    }
}


In this program, we have a swap() method that accepts two integer arguments. However, since Java passes arguments by value, the method only modifies copies of the original variables. The original variables x and y are not modified. The output of the program is:


2. Passing by Reference

In this example, we have a class with a setValue() method that accepts an integer array argument and sets its first element to a specified value.


public class Example2 {
    public static void setValue(int[] arr, int value) {
        arr[0] = value;
        System.out.println("Inside setValue method: arr[0] = " + arr[0]);
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        System.out.println("Before setValue: arr[0] = " + arr[0]);
        setValue(arr, 5);
        System.out.println("After setValue: arr[0] = " + arr[0]);
    }
}


In this program, we have a setValue() method that accepts an integer array argument. Since Java passes object references by value, the method modifies the original array object. The output of the program is:



3. Returning Values

In this example, we have a method that returns the maximum value of two integers.


public class Example3 {
    public static int max(int a, int b) {
        if (a > b) {
            return a;
        } else {
            return b;
        }
    }

    public static void main(String[] args) {
        int x = 10;
        int y = 20;
        int max = max(x, y);
        System.out.println("The maximum value is: " + max);
    }
}

In this program, we have a max() method that accepts two integer arguments and returns the maximum value. The main() method calls the max() method and stores the returned value in a variable. The output of the program is:


4. Returning Objects

In this example, we have a class Person with a constructor that accepts a name and age, and a getInfo() method that returns a string with the person's name and age.


.
.
.
.
.

{ THANK YOU }




Comments