1

Beginner learner of Java here. Am I right to say that int i is passed into int n1, int j is passed into int n2? But my output is After swapping,i is 1, j is 2 why can't my variables swap? Edit 1: After viewing other posts, some say that there is no such thing as a swapping method for primitive data? Then why did my instructor create this swap method, for confusion?

    int i = 1;
    int j = 2;
    swap(i,j);
    System.out.println("After swapping,i is " +i + ", j is " + j);
    }

public static void swap(int n1, int n2) {
    int temp = n1;  //temp =1
     n1 = n2;  //n1 = 2
     n2= temp; //n2 = 1


  • 2
    because you are changing nothing but the values of your local variables in your swap method – Stultuske Apr 11 '19 at 06:26
  • 3
    Search the Internet for "pass by value" versus "pass by reference". – Abra Apr 11 '19 at 06:27
  • swapped values are restricted to the scope of swap method only , you have to either return the swapped values from swap method in an array or swap directly without using method – vrooom Apr 11 '19 at 06:44

1 Answers1

0

You aren't affecting the values when passing variables by value to a method, you can move the swapping code to original method:

int i = 1;
int j = 2;
int temp = i; 
i = j;  
j = temp; 
System.out.println("After swapping,i is " +i + ", j is " + j);

Or use several answers in this question on swapping using method

Ori Marko
  • 56,308
  • 23
  • 131
  • 233