Write a class CallByValue to accept two integers from user and swap the values – use call by value.

0

Assignment: Module 03 - Part 01

Write a class CallByValue to accept two integers from user and swap the values – use call by value.
Assignment: Module 03 - Part 01

01. Write a class CallByValue to accept two integers from user and swap the values – use call by value.

Input: enter 2 numbers

11, 3

Output: Before calling method x=11y=3

From method x=12 y =4

After calling method x=11 y=3

Code:

import java.util.Scanner;

public class CallByValue {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter first number: ");
        int x = sc.nextInt();
        System.out.print("Enter second number: ");
        int y = sc.nextInt();

        System.out.println("Before calling method x=" + x + " y=" + y);
        swap(x, y);
        System.out.println("After calling method x=" + x + " y=" + y);
    }

    public static void swap(int a, int b) {
        int temp = a;
        a = b;
        b = temp;
        System.out.println("From method x=" + a + " y=" + b);
    }
} 
This code will output:
Enter first number: 11
Enter second number: 3
Before calling method x=11 y=3
From method x=3 y=11
After calling method x=11 y=3
 
As you can see, the values of x and y are passed to the swap method as arguments, but since Java uses call by value, the values of the variables x and y in the main method are not affected by the swap method, because the method is working with copies of the original values and not the original variables themselves. Therefore, after the swap method is called, the values of x and y in the main method remain the same.

👉Java Fundamentals Assignments👈

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
✨ Updates