I checked on debugging mode that value array have only 4 object on end method but when program went back on main method, after executeDefragmentation(), still printing full array with null.
package en.codegym.task.pro.task10.task1012;
import java.util.Arrays;
import java.util.Objects;
/*
Memory defragmentation
*/
public class Memory {
public static void main(String[] args) {
String[] memory = {"object15", null, null, "object2", null, null, null, "object32", null, "object4"};
executeDefragmentation(memory);
System.out.println(Arrays.toString(memory));
}
public static void executeDefragmentation(String[] array) {
int newStringLength = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != null)
newStringLength++;
}
String[] newMemory = new String[newStringLength];
int j = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
newMemory[j] = array[i];
j++;
}
}
array = newMemory;
}
}