People say that primitives are passed by value, and objects are passed by reference. This is incorrect. To be precise,
PRIMITIVES AND OBJECT REFERENCES ARE PASSED BY VALUE
Consider the following program
class PassByValue1{
private static void someMethod(int i){
i = 20;
}
public static void main(String[] args){
int someInt = 10;
System.out.println("Before calling someMethod(), someInt: " + someInt);
someMethod(someInt);
System.out.println("After calling someMethod(), someInt: " + someInt);
}
}
Output
D:\Dropbox\practice\blog>javac PassByValue1.java
D:\Dropbox\practice\blog>java PassByValue1
Before calling someMethod(), someInt: 10
After calling someMethod(), someInt: 10
We see that primitives are indeed passed by value. No surprises there...
Now consider a String object:
class PassByValue2{
private static void someMethod(String s){
s = null;
}
public static void main(String[] args){
String someString = "Some text";
System.out.println("Before calling someMethod(), someString: " + someString);
someMethod(someString);
System.out.println("After calling someMethod(), someString: " + someString);
}
}
Output:
D:\Dropbox\practice\blog>javac PassByValue2.java
D:\Dropbox\practice\blog>java PassByValue2
Before calling someMethod(), someString: Some text
After calling someMethod(), someString: Some text
Inside someMethod(), s points to the same String object as someString. Then s simply points to null as someMethod() returns.
Arrays are objects as well. Consider this:
import java.util.Arrays;
class PassByValue3{
private static void someMethod(int[] ia){
ia[2] = 20;
}
public static void main(String[] args){
int[] someIntArray = {0, 1, 2, 3};
System.out.println("Before calling someMethod(), someIntArray: " + Arrays.toString(someIntArray));
someMethod(someIntArray);
System.out.println("After calling someMethod(), someIntArray: " + Arrays.toString(someIntArray));
}
}
Output
D:\Dropbox\practice\blog>javac PassByValue3.java
D:\Dropbox\practice\blog>java PassByValue3
Before calling someMethod(), someIntArray: [0, 1, 2, 3]
After calling someMethod(), someIntArray: [0, 1, 20, 3]
D:\Dropbox\practice\blog>
Again as someMethod() is called, ia points to the same array object referenced by someIntArray. We just modify the array using ia.
No comments :
Post a Comment