1

I can declare a 2D array of size 10^9*10^9 but when for a given test case which requires this size throws an exception of Exception in thread "main" java.lang.OutOfMemoryError: Java heap space and yes if it leads to complete memory usage then why are able to instantiate such arrays?

Aker Abos
  • 21
  • 4
Dhruv Modi
  • 11
  • 1
  • 8
    Well, you didn't instantiate it, you only declared it. It gave an OOM error when it tried to instantiate it. – KevinO Jun 05 '17 at 18:16

2 Answers2

4

java.lang.OutOfMemoryError is a run-time error. Exceptions and errors of this kind are reserved for situations when it is not possible for the compiler to decide if an operation is possible or not.

The decision to throw out-of-memory error is made by the running JVM at the time when you attempt to instantiate the object. If you run the same program on a system with more memory, or let your running JVM use more memory by increasing heap size (how?), the program may run to completion without throwing the error.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

One aspect worth mentioning: of course some level of checking takes place at compile time: you can only use int values when declaring the array size.

The compiler will prevent you from using a long value there, and of course will not allow when you go for a negative number (when using literals).

But as the other answer says: the compiler accepting your code isn't the same as reality at runtime accepting your input.

GhostCat
  • 137,827
  • 25
  • 176
  • 248