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?
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.