Reputation: 4989
public Class A {
public static String s = "s";
public static int i = 0;
public int j = 1;
public static String getStaticString() {
int k = 2;
return s;
}
public String getString() {
int l = 3;
return "something";
}
}
In Java
, static variables are stored in Perm
generation of Heap Segment
, and primitive local variables are stored in Stack Segment
.
So where is i
, j
, k
, l
stored? Where is function getString()
stored?
Upvotes: 3
Views: 2558
Reputation: 29213
These are implementation details and we can't know for sure what each implementation does, without first reading and understanding its source code. As far as my knowledge and experience goes, the most reasonable things to assume (for a desktop JVM) are along these lines:
s
and i
are static variables. Static variables are probably allocated on the heap, in the permanent generation. j
is stored inside instances of class A
. Class instances may live on the stack (if escape analysis for references can prove that the reference has automatic storage semantics - and they are small enough) or the heap (if escape analysis is not performed or is inconclusive or the instance is too large for the stack).k
is a local variable with automatic storage semantics, thus it should live on the stack. It's allocated when its containing method (getStaticString
) is entered and it's deallocated when its containing method is exited.l
has the same semantics as k
. The fact that its containing method (getString
) isn't static, is irrelevant.getString
(and any other piece of user code, regardless of its linguistic attributes as static, non-static, etc) has two representations:
Upvotes: 3