0

These look the same to me but why do they produce different outputs? I'm new to Java so bear with me!

This swap function works

//Swap 1 Output is "4,8"
public class SampleSwap {
public static void main(String[] args)
{   
    int a=8;
    int b=4;
    int temp;

    temp=a;
    a=b;
    b=temp;

   System.out.println("a:" +a);
   System.out.println("b:" +b);
}
}

This swap function does not work

//Swap 2 Output is "8,4" 
public class Swap {
public static void main(String[] args) {
    int a = 8, b = 4;
    swap(a, b);
        System.out.print(a + "," + b);
    System.out.println();
}

public static void swap(int a, int b) {
    int tmp = a;
    a = b;
    b = tmp;
}
}
hova
  • 1
  • 1

1 Answers1

2

Those parameters are passed by value. They don't change the originals.

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75