Assignment: Module 03- Part 01
![]() |
Assignment: Module 03- Part 01 |
09. Write a class CallByObject to accept two integer variable values and swap it
Input:
Enter the values of a and b 23, 12
Output:
After swapping A = 12, B = 23
class CallByObject {
void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
System.out.println("After swapping a = " + a + " and b = " + b);
}
}
public class Main {
public static void main(String[] args) {
CallByObject obj = new CallByObject();
Scanner sc = new Scanner(System.in);
System.out.print("Enter the value of a: ");
int a = sc.nextInt();
System.out.print("Enter the value of b: ");
int b = sc.nextInt();
obj.swap(a, b);
}
}
In the above code, we create a class 'CallByObject' with a method 'swap' which accepts 2 integers and swaps their values. In the main method, we create an object of the 'CallByObject' class, take input from user for the values of a and b, then call the swap method with the values of a and b passed as arguments. The output of the above code is
"After swapping a = 12 and b = 23"
Note: This is a call by value method which means the original values of a and b passed in the main method will not be changed. In case you want to change the original values you need to pass the variables as reference using 'Call by Reference'.