Do uninitialized primitive instance variables use memory?

前端 未结 6 1906
庸人自扰
庸人自扰 2020-12-14 14:37

In Java, does it cost memory to declare a class level instance variable without initializing it?
For example: Does int i; use any memory if I don\'t initial

6条回答
  •  悲&欢浪女
    2020-12-14 14:57

    All members defined in your classes have default values, even if you don't initialize them explicitly, so they do use memory.

    For example, every int will be initialized by default to 0, and will occupy 4 bytes.

    For class members :

    int i;
    

    is the same as :

    int i = 0;
    

    Here's what the JLS says about instance variables :

    If a class T has a field a that is an instance variable, then a new instance variable a is created and initialized to a default value (§4.12.5) as part of each newly created object of class T or of any class that is a subclass of T (§8.1.4). The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object (§12.6) has been completed.

提交回复
热议问题