java參數傳遞之值傳遞和引用傳遞
更新時間:2021年02月08日 16:22:01 作者:leo_host
這篇文章主要介紹了java參數傳遞之值傳遞和引用傳遞,引用了兩個代碼實例來講解,有感興趣的同學可以研究下
值傳遞
當調用方法進行值傳遞時,方法內部會產生一個局部變量,在方法內部使用局部變量的值,并不影響傳入原來數據的值,包括在使用基本數據類型的包裝類。
public class Assc
{
public static void main(String[] args)
{
int x1=1;
add(x1);
System.out.println("最終"+x1);//1
Integer x2=new Integer(1);
sub(x2);
System.out.println("最終"+x2);//1
}
public static void add(int x) {
x++;
System.out.println(x); //2
}
public static void sub(Integer x) {
x--;
System.out.println(x);//0
}
}
引用傳遞
當調用方法時使用引用類型參數時,使用的是與傳入參數同一地址的數據,在方法內部進行參數的修改,會造成原來數據的改變(String 類型除外)
String類型數據在傳入時,進行的操作是在字符串常量池中新建一個字符串,并不影響原先字符串的值
public class Assc
{
public static void main(String[] args)
{
String str="hello";
combine(str);
System.out.println("最終"+str);//hello
StringBuilder sb=new StringBuilder("nihao");
combine2(sb);
System.out.println("最終"+sb);//nihaoworld
}
public static void combine(String str) {
str+="world";
System.out.println(str);//helloworld
}
public static void combine2(StringBuilder str) {
str.append("world");
System.out.println(str);//nihaoworld
}
}
到此這篇關于java參數傳遞之值傳遞和引用傳遞的文章就介紹到這了,更多相關值傳遞和引用傳遞內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java畢業(yè)設計實戰(zhàn)之平行志愿管理系統(tǒng)的實現(xiàn)
這是一個使用了java+Springboot+Maven+mybatis+Vue+Mysql開發(fā)的圖片平行志愿管理系統(tǒng),是一個畢業(yè)設計的實戰(zhàn)練習,具有志愿管理該有的所有功能,感興趣的朋友快來看看吧2022-02-02

