简体   繁体   中英

When does memory gets allocated to the object(POJO) in Java

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

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

Does memory gets allocate when I create object Abc abc = new Abc() ie 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; ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM