0

In c, uninitialized static variable don't take space in executable file.

What about Java? Does a static variable take space in .class file?

Tip: The question is about disk space, not memory.

Eric
  • 22,183
  • 20
  • 145
  • 196
  • 1
    The only space this variable occupies in the class file will be some chars that the JVM will read. If you refer if the uninitialized variable will occupy some space of memory when the class is loaded and executed by the JVM, it depends if the variable is a primitive or an object reference. – Luiggi Mendoza May 25 '15 at 02:50
  • 1
    A Java .class file contains a *description* of the class. A static variable necessarily requires a description of its size, type, and initialization info, and generally it's name will be recorded as well. – Hot Licks May 25 '15 at 03:04

2 Answers2

2

All fields have an entry in the classfile giving the name, type, flags (final, public, volatile, static, etc.), and other data.

If you think about it, it has to be this way. Java isn't C, where the variable is just a location in bss or whatever. You have reflection as well as runtime type checking, so all that information has to be maintained.

If the field is initialized, there will be additional data in the classfile to do the initialization (either a ConstantValue attribute or bytecode in the method). However, even an uninitialized field has to have the field entry in the classfile.

Antimony
  • 37,781
  • 10
  • 100
  • 107
-1

Yes, they will take up memory. All variables in java will have default values assigned to them even if you do not initialize it. So,

int i;

will take up memory in this instance. Here is some further reading: Do uninitialized primitive instance variables use memory?

Community
  • 1
  • 1
Nick P
  • 347
  • 1
  • 4
  • 13
  • 1
    The question is not asking about memory, but about compiled file, which is on disk. – Eric May 25 '15 at 03:20
  • When you write a new java source which refers to the static variable, then you compile the source, javac must refer to the static variable defined in .class file. So .class file must have its definition (data type and actual value), .class files are also serves as a header file in C. –  May 25 '15 at 04:20
  • In addition to the question not asking about memory, but disk space: it is asking about static variable, not instance variables. – Erwin Bolwidt May 25 '15 at 06:08