Simple swap in Java [duplicate]

这一生的挚爱 提交于 2019-12-12 03:59:33

问题


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;
}
}

回答1:


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



来源:https://stackoverflow.com/questions/32431061/simple-swap-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!