[JAVA basics] What's the reason for garbage collection?

Asked 2 years ago, Updated 2 years ago, 27 views

int[ ] n = new int [10];

for(int i=0;  i<10; i++) {

    Scanner s = new Scanner(System.in);
    n[i] = s.nextInt();
    }

In this code, while the for statement is repeated 10 times, the nine objects assigned to new Scanner (System.in); become garbage

Why is it garbage when you put objects in 10 array elements one by one?

Is there no value between n[0] and n[8] for garbage?

java

2022-09-22 18:17

1 Answers

int[] n = new int [10];

for(int i=0;  i<10; i++) {

    Scanner s = new Scanner(System.in);
    n[i] = s.nextInt();
}

Please look at the code carefully.

n is an array of ints. That is, the int value is stored.

The s object in the for repeat statement is intended to obtain only the int value, and the int value obtained is stored in the array. The scope of the s object is limited to the for iteration statement.

If for repeats again, s is assigned another new object. Previous objects s become inaccessible objects and garbage targets.

In other words, the values in the array and the Scanner object are irrelevant. The int value is copied and stored in the array, and the Scanner object is gc-targeted and cleaned.

In languages without gc such as c/c++, the above code is memory leak (because s is not deleted), but Java is very convenient because gc is provided.


2022-09-22 18:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.