0
Class Abc {
    Integer a;
    Integer b;
    Integer c;
    getters();
    setters();
}

Does memory gets allocate when I create object Abc abc = new Abc() i.e. 12 byte(4 byte for integer) or when I set some values to the variables like setA(10).?

Gajendra24
  • 43
  • 2
  • 10
  • Assuming you mean heap memory and not stack: for this class, you get 3x8 = 24 bytes allocated when you call `new` (Java references are well known to typically require 8 bytes, and you have three of them) and then another 4 bytes at least for each `Integer` when you create it. Plus there's a one time allocation of the `Class` itself when the class file is loaded (dunno how many bytes, look at the class file). – markspace Apr 11 '17 at 01:00
  • Memory is allocated when the object is initialized (i.e. `new Object()`). However, an `int` requires 4 bytes each, and you're using the `Integer` wrapper (boxed) class which will require even more memory. – Jacob G. Apr 11 '17 at 01:00
  • 1
    Memory is allocated when you call `new`. – Thomas Fritsch Apr 11 '17 at 01:00
  • this post may be helpful to understand. [link](http://www.journaldev.com/4098/java-heap-space-vs-stack-memory) – Rajith Pemabandu Apr 11 '17 at 01:01
  • Memory for instance variables allocated during object creation, for static variables created during class loading – Yohannes Gebremariam Apr 11 '17 at 01:01
  • Possible duplicate of [Steps in the memory allocation process for Java objects](http://stackoverflow.com/questions/320980/steps-in-the-memory-allocation-process-for-java-objects) – Rajith Pemabandu Apr 11 '17 at 01:01

1 Answers1

1

Does memory gets allocate when I create object Abc abc = new Abc() i.e. 12 byte(4 byte for integer).

Yes. More specifically, it gets allocated immediately before the constructor chain for the Abc class is called.

However, the space allocated also includes some header information, and the amount in your example will depend on whether the JVM is using 32bit or 64bit addresses for references. (The Integer type is a reference type!)

(Assuming 32bit references, the size will probably be 3 x 4 bytes + 8 bytes header + 4 bytes padding; i.e. 24 bytes. However this is JVM implementation specific.)


or when I set some values to the variables like setA(10).

That will depend on the signature of the setA method, and the way that it is implemented. The issue is whether there is autoboxing of int -> Integer and where / when that occurs.

However in all situations the Integer objects that (may be) allocated are not part of the Abc object. The Abc object has fields to hold references to Integer objects, and the space for those fields is part of the Abc object ... which means it is allocated when that object is allocated not when the field is set.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216