I am working on an assignment, and while I have completed the beginning part of it I am am stuck on the last step of it. This is what i have to do for the last part.
Modify the main method so after the call to the
swap
method, the actual values ofnum1
andnum2
are swapped inmain
and show this in the output. The output will have one additional line, that shows the values of the two numbers inmain
after they are swapped. The new line in the output needs to be "After swapping the numbers in main method, num1 is 2 and num2 is 1".
Code:
public class PassByValue {
/** Main method */
public static void main(String[] args) {
// Declare and initialize variables
int num1 = 1;
int num2 = 2;
System.out.println("Before invoking the swap method, num1 is " +
num1 + " and num2 is " + num2);
//invoke the swap method to attempt to swap two variables
swap(num1, num2);
System.out.println("After invoking the swap method, num1 is " +
num1 + " and num2 is " + num2);
}
/** Swap two variables */
public static void swap(int n1, int n2) {
System.out.println("\tInside the swap method");
System.out.println("\t\tBefore swapping, n1 is " + n1
+ " and n2 is " +n2);
// Swap n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;
System.out.println("\t\tAfter swapping, n1 is " + n1
+ " and n2 is " + n2);
}
}