我们在java中使用引用调用或按值调用的内容? [英] what we use call by reference or call by value in java ?

查看:154
本文介绍了我们在java中使用引用调用或按值调用的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好



你能告诉我我们在java中通过引用使用什么或者在java中按值调用吗?



其实我举个例子。

Hello

can you please tell me what we use in java call by reference or call by value in java ?

Actually i take example.

package stringapp;

public class StringApp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("-----");
        String ss="Naveen";
         System.out.println("-----"+ss);
         change (ss);
          System.out.println("-----"+ss);
        
        // TODO code application logic here
    }
    public static void change(String p){
    p+="sharma";
    }
}





当我拿字符串然后调用更改方法之后我打印字符串它将显示相同naveen;



但是当我拿着StringBuilder的字符串时,它会打印出naveensharma

为什么?



为什么string byilder打印naveen sharma?它通过引用来调用?



已添加代码块[/编辑]



When i take string then call change method after that i print string it will show same "naveen";

But when i take StringBuilder instand of string it will print "naveensharma"
Why ?

why string byilder print naveen sharma ? it call by reference?

Code block added[/Edit]

推荐答案

仅限于价值,在所有情况下。



这个Java限制可以通过大多数类型都是引用类型来补偿。传递基本类型(如数字)时,无法修改调用者传递的值。如果修改方法参数,则只修改堆栈上副本的值,并且调用者仍具有相同的原始值。



参考完全相同类型,在这种情况下,您无法修改引用本身。但你仍然可以使用它的一些成员修改引用的对象。比如,如果修改引用对象的某个字段,则不要修改引用,而是修改对象本身。被调用的代码将获得相同的对象(引用),但已修改。



-SA
Only by value, in all cases.

This Java limitation is compensated by the fact that most types are reference types. When you pass a primitive type, such as number, you cannot modify the value passed by a caller. If you modify the method parameter, you modify only the value of the copy on stack, and the caller still have the same original value.

Exactly the same happens with reference type, in this case, you cannot modify the reference itself. But you still can modify the referenced object my using some of its members. Say, if you modify some field of referenced object, you don''t modify the reference, but modify the object itself. The called code will get the same object (reference), but modified.

—SA


请参阅 http://docs.oracle.com/javase/tutorial/java/index.html [ ^ ]。


这篇关于我们在java中使用引用调用或按值调用的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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