Created
April 28, 2013 20:31
-
-
Save blouerat/5478308 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
with a new array: 10 | |
with a new array and new value: 10 | |
with a new value: 42 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PlayingWithArrays { | |
public static void setToNewArray(int[] x) { | |
x = new int[1]; | |
/* | |
x is passed by value, assigning it a new array won't change its state outside the body of the function | |
*/ | |
} | |
public static void setToNewArrayAndValue(int[] x) { | |
x = new int[1]; | |
x[0] = 42; | |
/* | |
x is a new array only within the function once again (passed by value) | |
so setting the first element of that array to 42 only change the internal state of the function, not outside | |
*/ | |
} | |
public static void setValue(int[] x) { | |
x[0] = 42; | |
/* | |
finally, changing the value of an element of the array changes the state outside the scope of the function, like with objects | |
*/ | |
} | |
public static void main(String[] args) { | |
int[] x = {10, 20, 30}; | |
setToNewArray(x); | |
System.out.println("with a new array: " + x[0]); | |
setToNewArrayAndValue(x); | |
System.out.println("with a new array and new value: " + x[0]); | |
setValue(x); | |
System.out.println("with a new value: " + x[0]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment