Using objects across methods in the same class

Hi there, I’m very new to Java and while learning about Loops, I noticed in the following exercise: https://www.codecademy.com/courses/learn-java/lessons/learn-java-loops/exercises/removing-elements-during-traversal that the first method in the class uses an object (not sure if that is the correct term for it) lunchBox, and the second method uses lunchContainer. As far as I can see it is not defined anywhere in this class that lunchContainer corresponds to lunchBox, yet the first method implies that we are pulling in the various strings of lunchContainer to check for “ant”, but instead of calling lunchContainer, we call lunchBox. So I am confused how that first method knows what lunchBox contains as an ArrayList, if nowhere it is assigned to lunchContainer?

The ArrayList in lunchContainer is also assigned to lunchBox
because lunch Container is the argument of the method (and its an object)
and lunchBox is the parameter that matches with that argument

The first (and only) parameter of the method is lunchBox

  public static ArrayList<String> removeAnts(ArrayList<String> lunchBox) {

The first (and only argument) when you call that in the main method is lunchContainer

removeAnts(lunchContainer);

and since this is an ArrayList (which is an object)
when the method is executed, lunchbox is assigned to the same thing as lunchContainer

1 Like