Java is Strictly Pass by Value. For example, if I pass an integer to a method that changes the value of it and don't return the value, the integer in the main method would not be changed.
However, when I passed an ArrayList
to a method that adds items to the list, it turned out that the method changed the ArrayList in the main method.
public class test {
public static void main(String[] args) {
// create a array list
ArrayList<String> item = new ArrayList<String>();
addItems(item);
System.out.println("Items in the main method are: ");
for (int i = 0; i < item.size(); i++) {
System.out.println(item.get(i));
}
System.out.println("\n***************************\n");
int num = 0;
plusOne(num);
System.out.println("The value of num in the main method is: " + num);
}
//add two items to arrayList
public static void addItems(ArrayList<String> item) {
item.add("Item #1");
item.add("Item #2");
System.out.println("Items in the addItems method are: ");
for (int i = 0; i < item.size(); i++) {
System.out.println(item.get(i));
}
}
//add one to num
public static void plusOne(int num) {
num = num +1;
System.out.println("The value of num in the plusOne method is: " + num);
}
}
Here's the output:
Items in the addItems method are:
Item #1
Item #2
Items in the main method are:
Item #1
Item #2
***************************
The value of num in the plusOne method is: 1
The value of num in the main method is: 0
This is confusing.
why addItems()
changed item
while plusOne()
didn't change num
?
Could someone explain it? Thank you!