This question already has an answer here:
- Is Java “pass-by-reference” or “pass-by-value”? 83 answers
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;
}
}