`
llystar
  • 浏览: 63910 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

一个参数传值问题

 
阅读更多

 

public class Test {
  
     /**
      * @param args
      */
     public static void main(String[] args) {
         // TODO Auto-generated method stub
         //StringBuffer str=new StringBuffer("World");
         String str=new String("World");
         char ch[]={'h','e','l','l','o'};
         change(str,ch);
         System.out.print(str+"and");
         System.out.println(ch);
          
     }
     public static void change(String str,char ch[]){
         //str.append("change");
         str="change";
         ch[0]='c';
     }
  
}
这个程序的输出为worldandcello
使用String str =new String();创建的不是一个对象吗,str为一个引用。那调用change(str,ch)为什么不是传地址。

 

 

 

发信人: IcyFenix ().println("helloworld"), 信区: Java
标  题: Re: 求教一个参数传值问题
发信站: 水木社区 (Mon Oct 31 15:34:32 2011), 站内
  
先明确一点,在jvm里面,没有“按引用传递”这回事,只有对reference数据进行值传
递。
可以对着你的代码来说明这点:
String str=new String("World");  // 假设String("World")的地址为0x1111,那有一
个reference类型的局部变量A=0x1111.
char ch[]={'h','e','l','l','o'};  // 同理,假设数组起始地址为0x2222,那有一
个reference类型的局部变量B=0x2222.
change(str,ch);   // 方法调用,新建栈帧,栈帧中第0、1个局部变量C、D赋值为
0x1111、0x2222
str="change";     // 把局部变量C的值改为0x3333,但是这并不影响原来A的值继续
=0x1111
ch[0]='c';        // castore指令执行时,操作数栈上的3个参数是0x2222、0、
'c',因此castore把地址在0x2222的数组的第0个元素赋值为'c'。
不知道这样讲是否能解答你的疑问。
  
关于invokeinterface的问题:
inovkeinterface中的count参数用于确定方法参数个数,这个完全可以在方法描述符中
获取,其他几个invoke指令也就是从方法描述符中取的。而inovkeinterface指令保留
这个count完全是历史原因。见《JVMS Java SE 7》介绍interinterface这段:
The count operand of the invokeinterface instruction records a measure of  
the number of argument values, where an argument value of type long or type  
double contributes two units to the count value and an argument of any other  
type contributes one unit. This information can also be derived from the  
descriptor of the selected method. The redundancy is historical.
另外,在jdk7中加入的invokedynamic中,那2个固定为0的直接操作数,也是由于这
个“历史原因”,因为interfacedynamic最初是以inovkeinterface为模板设计的。

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics