Skip to content

Instantly share code, notes, and snippets.

@ThatJoeMoore
Last active September 1, 2015 04:47
Show Gist options
  • Save ThatJoeMoore/b061d08e6444d0a7a8f9 to your computer and use it in GitHub Desktop.
Save ThatJoeMoore/b061d08e6444d0a7a8f9 to your computer and use it in GitHub Desktop.
Simple example of passing by value (primitive) vs reference (arrays and objects)
/**
* Licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
* (see http://creativecommons.org/licenses/by-nc-sa/4.0/)
*/
import java.util.Arrays;
/**
* @author Joseph Moore (joseph_moore@byu.edu)
*/
public class ReferenceVsValue {
public static void main(String... args) {
int i = 1;
int[] array = new int[]{1, 2, 3};
Foo foo = new Foo();
foo.bar = "bar";
int y = array[0];
array[0] = 2;
System.out.println(y);
Foo[] foos = new Foo[] {
new Foo(),
new Foo()
};
Foo f = foos[0];
foos[0].bar = "something";
System.out.println(f);
f.bar = "changed again";
System.out.println(foos[0]);
System.out.println("i before: " + i);
changeInt(i);
System.out.println("i outside: " + i);
System.out.println("array before: " + Arrays.toString(array));
changeArray(array);
System.out.println("array outside: " + Arrays.toString(array));
changeObject(foo);
System.out.println("outside: " + foo);
}
public static void changeInt(int i) {
i += 1;
System.out.println("i in method: " + i);
}
public static void changeArray(int[] array) {
array[0] = 42;
System.out.println("in method: " + Arrays.toString(array));
}
public static void changeObject(Foo foo) {
foo.bar = "ciao";
System.out.println("in method: " + foo);
}
public static final class Foo {
String bar;
@Override
public String toString() {
return "Foo{" +
"bar='" + bar + '\'' +
'}';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment