在java中交换对象 [英] swapping of objects in java

查看:447
本文介绍了在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.

这篇关于在java中交换对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆