1

Take any OOPs language with referencing as basic structure like java and c#.

For fast execution, they also support primitive types like int and char. I think this is done by storing them on the stack. and object types on the heap.

so for this:

class B
{
 ...
}

class A
{
   int a;
   B b;
}

Is A.a is in stack or on heap ?

Ashish Negi
  • 5,193
  • 8
  • 51
  • 95
  • http://stackoverflow.com/questions/3646632/does-the-java-primitives-go-on-the-stack-or-the-heap see this answer – Petr Mensik Jul 31 '12 at 08:27

3 Answers3

1
  • Class objects, including method code and static fields: heap.
  • Objects, including instance fields: heap.
  • Local variables and calls to methods: stack

But for java6 there are situations when objects are created on stack.

proof: http://docs.oracle.com/javase/specs/jvms/se5.0/html/Concepts.doc.html#29375

Observer
  • 710
  • 10
  • 14
1

The basic answer is that all local variables are on the stack and everything else is on the heap. However, as of Java 7 the compiler will perform a technique known as Escape analysis that checks whether an object is used strictly within a method (and doesn't escape that method), and upon finding such an object, will allocate its storage on the stack. This behavior was introduced with Java 6, Update 14, but not activated by default.

This, as many other examples, shows you that Java Language Specification is one thing and implementations another. As long as an implementation behaves as defined by the JLS, it is legit.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
0

Only local variables are stored in stack, the others are in heap.

xdazz
  • 158,678
  • 38
  • 247
  • 274