问题
import java.util.Arrays;
public class Test {
public static void main(String... args) {
String[] strings = new String[] { "foo", "bar" };
changeReference(strings);
System.out.println(Arrays.toString(strings)); // still [foo, bar]
changeValue(strings);
System.out.println(Arrays.toString(strings)); // [foo, foo]
}
public static void changeReference(String[] strings) {
strings = new String[] { "foo", "foo" };
}
public static void changeValue(String[] strings) {
strings[1] = "foo";
}
}
Can anyone explain these questions?
- What is Strings[]. Is it a String Object or String Object containing array of Objects.
- What does the changeReference() and changeValue() functions do and return?
- Does Java support Pass by Reference?
回答1:
stringsis an array ofStrings. Arrays are objects for our purposes here, which means they are a reference type.changeReferencedoes nothing useful. It receives a reference tostrings, but it receives that reference by value. Reassigningstringswithin the function has no effect on thestringsbeing passed in -- it just replaces the local copy of the reference, with a reference to a new array.changeValue, on the other hand, modifies the array object referred to bystrings. Since it's a reference type, the variable refers to the same object.No, "pass by reference" is not supported. Java can pass references around, but it passes them by value. Summary being, you can change the object being passed in, but you can't replace the object in such a way that the caller will see it.
回答2:
What is Strings[]. Is it a String Object or String Object containing array of Objects.
It’s neither. It’s an object (well, actually it’s a type) that references an array of strings.
What does the chanfeReference and changeValue function do and return?
Please try it yourself to see the effect.
Does Java support Pass by Reference?
No. Java is always pass by value.
回答3:
What is String[]. Is it a String Object or String Object containing array of Objects.
String[] is an array of String (and String is an Object).
What does the
changeReferenceandchangeValuefunction do and return?
In changeReference() java changes the reference of strings to an new string array. In changeValue(), java changes the value of the first element of strings array.
Does Java support Pass by Reference?
Java supports Pass by Value. As stated on JavaWorld:
Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
回答4:
String[]is an array of String objectschangeReferencechanges the refence to the arraystringsto a new refence to a new array which, in this case, contains the same thing, but the reference in the memory is in another place.- Pass by Reference is not supported in Java
来源:https://stackoverflow.com/questions/6277740/pass-by-value-in-java