在java中交换对象

在java中交换对象

问题描述:

我已经研究过java是通过引用传递但是当我执行下面的代码时,字符串在主方法中没有交换为什么?

I have studied that java is pass by reference but when I execute following code the strings are not swapped in main method why?

static void swap(String s1, String s2){
    String temp = s1;
    s1=s2;
    s2=temp;
}

public static void main(String[] args) {
    String s1 = "Hello", s2 = "world";
    swap(s1, s2);
    System.out.println(s1 + s2);
}


你研究过错误的来源。 Java是按值传递的。 此处是您可以学习的更多资源。从此处,您可以找到与您类似的示例的讨论。

You studied wrong sources. Java is pass by value. Here is one source more you can study. And from here you can find discussion about example similar to yours.