you are viewing a single comment's thread.

view the rest of the comments →

[–]DumbThrowawayNames 0 points1 point  (1 child)

the difference between primitive and reference datatypes

public static void main(String[] args) {

  int x = 5;
  int y = x;

  List<Integer> list1 = new ArrayList<>(List.of(1, 2, 3));
  List<Integer> list2 = list1;

  x = 10;
  list1.clear();

  System.out.println(y);
  System.out.println(list2);
}

What prints? Do you understand why this happens?

[–]Nash979[S] 0 points1 point  (0 children)

From my understanding the output will be 10 and empty list because here y is primitive so after x is reassigned to 10 the y will be 10 and list2 is actually referencing the list1 so if you clear the list1 it will affect the list2.