0

I have the below code:

public class Main {

  public static List<Integer> ODD_NUMBERS = new ArrayList<Integer>();

  public static void main(String[] args) {

    for(int i =0;i<10;i++)
      ODD_NUMBERS.add(2*i+1);

    System.out.println("1. oddNumbers:    "+String.valueOf(ODD_NUMBERS));

    addEvenNumbers(ODD_NUMBERS);

    System.out.println("3. oddNumbers:    "+String.valueOf(ODD_NUMBERS));
  }

  private static void addEvenNumbers(List<Integer> listOfNumbers) {

    for(int i =0;i<10;i++){
      listOfNumbers.add(2*i);
    }

    System.out.println("2. listOfNumbers: "+String.valueOf(listOfNumbers));
  }

}

and the following outputs:

1. oddNumbers:    [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
2. listOfNumbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
3. oddNumbers:    [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

I have some difficulties in understanding how a static field is changing!!!

Given that I have ODD_NUMBERS as static list of integer numbers which is filled by the odd numbers. But then I send this list as a parameter to the addEvenNumbers method which adds some Even integers into it and the result of the print inside the method is:

listOfNumbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

But, when i back to the main() method and print the static variable ODD_NUMBERS then it has the same value as also changed to the below values listOfNumbers like below :

 [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

The fact that listOfNumbers and ODD_NUMBERS have identical values surprises me, because the value listOfNumbers is a parameter of addEvenNumbers and it must have no effect out of this block of code. Also, the method never returns anythings.

So, my question is:

Is it because the parameter of method (listOfNumbers) is referenced by an static parameter ? Can you explain how the static variable changes ?

Sal-laS
  • 11,016
  • 25
  • 99
  • 169
  • This has nothing to do with `static`, it’s the regular semantics of copying references in Java. – Konrad Rudolph Jul 27 '21 at 09:38
  • It has nothing to do with static variables, and everything with [reference semantics](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value). – Thomas Jul 27 '21 at 09:38
  • Apologies for perpetuating a common misuse of terminology. – Thomas Jul 27 '21 at 09:40

0 Answers0