java函数传递对象

来源:互联网 发布:数据库保险箱 编辑:程序博客网 时间:2024/06/03 17:22
package tao.leetcode;import java.util.ArrayList;import java.util.Scanner;/** * Created by Tao on 2017/7/30. */public class MyLeetcode {    int[] arr = {1,2};    String str = "hello";    public static void main(String[] args) {        MyLeetcode my = new MyLeetcode();        my.exchange(my.arr, my.str);        System.out.println(my.arr[0]);        System.out.println(my.str);    }    private void exchange(int[] arr, String str) {        arr[0] = 3;        str = "word";    }}

output:
3
hello

java在函数传递对象时,对于基本数据类型和对象变量操作不同。
基本数据类型:传递值得副本,副本变,本身不变
对象变量:传递引用副本,副本变,本身也变
String在java中是个特殊的类型,虽然是对象型变量,但String是不可变类,因此与值传递相同。

String是不可变类:

String str = "hello";str = str.concat(" word");

str最后指向“hello word”,但hello字符串仍然存在。