public class Test {
public static void main(String[] args){
int [] arr = new int[]{1,2};
String b=new String("abc");
f(b,arr);
System.out.println(b);
System.out.println(arr[0]);
}
public static void f(String b, int[] arr){
b+="de";
b=null;
arr[0] = 5;
}
}
Why the reference variable of the string doesn't behave like the reference variable of the array?.
I know string are immutable so operations on them creates new string but how about references to strings and how开发者_Python百科 the reference b still refer to the old value although it was changed to refer to something else in f() method.Object references in Java are passed by value. Assigning just changes the value, it does not alter the original object reference.
In your example arr[0]
is changed, but try arr=null
and you will see it has no effect after the method has returned.
Method call is called by value in Java, well there is long debate about this , But I think that we should consider in terms of implementation language of Java which is C/C++. Object references just pointers to objects, and primitives are the values.. Whenever a method is called, actual arguments are copied to formal parameters. Therefore, if you change pointer to reference another object , original pointer is not affected by this change, but if you change object itself, calling party can also see the changes, because both party are referring the same object..
Well, in your example, you are changing string reference to null in called method, but you are changing object referred by array reference.. These two operations are not the same, therefore they do have different consequences.. for example, if you change the code as below, they would be semantically same operation..
arr = null;
You cnanot change the argument for any method, however you can do the following.
public static void main(String... args) throws IOException {
String[] strings = {"Hello "};
addWorld(strings);
System.out.println("Using an array "+Arrays.toString(strings));
StringBuilder text = new StringBuilder("Hello ");
addWorld(text);
System.out.println("Using a StringBuilder '" + text+"'");
}
private static void addWorld(String[] strings) {
for(int i=0;i<strings.length;i++)
strings[i] += "World!";
strings = null; // doesn't do anything.
}
private static void addWorld(StringBuilder text) {
text.append("World !!");
text = null; // doesn't do anything.
}
prints
Using an array [Hello World!]
Using a StringBuilder 'Hello World !!'
精彩评论