In Java, is a global variable always put on the heap?
heap-memory, java
Solution
Java has a concept of PermGen space - this is the space used to store all class definitions, static variables, interned strings, etc. here is link
This Java heap memory is structured again into regions, called generations. The longer an object lives, the higher the chance it will be promoted to an older generation. Young generations(such as Eden on Sun JVM) are more garbage collected than older generations(survivor and tenured on Sun JVM). However, there is also some separate heap space called permanent generation. Since it is a separate region, it is not considered part of the Java Heap space. Objects in this space are relatively permanent. Class definitions are stored here, as are static instances.
A full description of PermGen space can also be found here, although note that this is changing with Java 8: here is link
Static variables are stored there, dynamically allocated things are stored in the regular heap.
(Note that even for the static array the things placed within the array are dynamically generated).
Your second example is better for this case though unless you really need to remember the contents of that array between calls. You are using up memory all the time to store an array that you only need while you are inside the method. Additionally by having the static data like that your method is not re-entrant. That means that if two threads call the method at the same time then they will interfere with each other and give bad results.
Problem
Also, how does having a static variable affect things? (If at all) For example: ``` class MyClass{ static int[][] data; static { data = new int[some number][some number]; /*read data into array*/ } static void run() { /*now use data here*/ } } ``` Is this put on the heap? Comparing that example with ``` class MyClass{ static void run() { int[][] data = new int[some number][some number]; /*now use data here*/ } } ``` How much difference is there between these two code examples? Please shed any insight.