A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© wangxiaocong 中级黑马   /  2015-6-6 14:21  /  717 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class StringTest1 {

  2.         public static void main(String[] args){

  3.                
  4.                 StringBuilder s1 = new StringBuilder("hello");
  5.                 StringBuilder s2 = new StringBuilder("world");
  6.                 method_1(s1,s2);
  7.                 System.out.println(s1+"---"+s2);
  8.         }
  9.        

  10.         public static void method_1(StringBuilder s1, StringBuilder s2){
  11.                 s1.append(s2);
  12.                 s1 = s2;
  13.                 System.out.println(s1);
  14.                 System.out.println(s2);
  15.         }
  16. }
复制代码

输出:
  1. world
  2. world
  3. helloworld---world
复制代码


为什么s1已经被s2赋值为world了 在main函数打印的时候还是helloworld??

评分

参与人数 1技术分 +1 收起 理由
lwj123 + 1

查看全部评分

6 个回复

倒序浏览
方法中的s1 s2和main中的s1 s2不是同一个变量.
一个是形参一个是实参.
s1 = s2;只是改变方法中s1的地址值
main中的都没有改变
你可以用s1.hashCode()输出他们指向的地址值就清楚了
回复 使用道具 举报
本帖最后由 lwj123 于 2015-6-6 15:44 编辑

StringBuffer在做为方法参数传递时,对于赋值操作只在方法内有效,调用StringBuffer的方法作用的效果是会影响源始值的。
回复 使用道具 举报
地址引用变啦对象没变
回复 使用道具 举报
学习了。。。
回复 使用道具 举报
字符串传递时值传递,没有改变原来s1
回复 使用道具 举报
我还是看不懂哦
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马