Skip to content

Instantly share code, notes, and snippets.

@daubac402
Created May 23, 2025 03:01
Show Gist options
  • Save daubac402/64b08505013e0d7aee30560cf0d31f52 to your computer and use it in GitHub Desktop.
Save daubac402/64b08505013e0d7aee30560cf0d31f52 to your computer and use it in GitHub Desktop.
Java Pass By Value Test
import java.util.*;
public class MyClass {
public static void main(String args[]) {
ArrayList<String> a = new ArrayList<>();
add1(a,"1");
System.out.println("a:" + a); // Guess the output
add2(a,"2");
System.out.println("a:" + a); // Guess the output
}
public static void add1(List<String> list, String str) {
list.add(str);
}
public static void add2(List<String> list, String str) {
list = new ArrayList<>();
list.add(str);
}
}
// OUTPUT HERE:
// a:[1]
// a:[1]
// In add1(), it will work correctly to add str to the a list.
// Because it continues to reference the original list, allowing modifications to persist.
// In add2(), it creates a new ArrayList then the local `list` point to that new object, it doesn't affect decreasedCv.
// The next adding also adds to that new object only.
// So the modification to original list is not persisted.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment