Junior — Middle
How can a memory shortage error be provoked in a Java application?
sobes.tech AI
Answer from AI
An OutOfMemoryError in a Java application can be triggered, for example, by creating a large number of objects without releasing references to them, which prevents the garbage collector from freeing memory. This often happens when elements are added uncontrollably to collections, such as in an infinite loop.
Example:
import java.util.ArrayList;
import java.util.List;
public class MemoryLeakExample {
public static void main(String[] args) {
List<byte[]> list = new ArrayList<>();
while (true) {
// Create 1MB arrays and add them to the list
list.add(new byte[1024 * 1024]);
}
}
}
In this example, the program will continuously allocate memory for new arrays and keep references to them, leading to heap overflow and throwing an OutOfMemoryError.