8

What is the difference in memory between a variable assigned to null and one not assigned?

I know that there is a difference in usage, but what is the difference in memory?

1
  • 1
    Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask
    – gnat
    Apr 6, 2015 at 12:34

3 Answers 3

12

There is no difference between the two "in memory."

From the Java Language Specification, 4.12.5. Initial Values of Variables :

Every variable in a program must have a value before its value is used:

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):

...

    • For all reference types (§4.3), the default value is null.

...

    • A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

Reference variables at the class or object level will be assigned a null value.

Reference variables at the method (stack) level will have an unspecified value (using the C++ term). In practice this is often null, but the standard does not specify what is in the reference variable, only that it must be assigned before use. Using a reference variable on the stack in any way other than assignment as its first use will result in a compile error.

4
  • When you declare a variable without initializing it to null, then initialize it inside a if-then block, the compiler tells you that the variable maybe uninitialized ahead in the code if the then block is not executed. If you initialize it to null the code compiles. Why is that given that " a reference not explicitly assigned a value will have the value null" ? Apr 6, 2015 at 12:39
  • @Snowman Isn't that an implementation detail? Only class variables, instance variables, and array components are required to be initialized to their default values. There's no requirement on local variables and you can't use them before they're initialized. If you were to look at an uninitialized local variable in memory you'd see whatever the implementation happens to do with it, which may not involve initializing it to null since it would be unnecessary work to do so.
    – Doval
    Apr 6, 2015 at 12:49
  • @Snowman - Since it's illegal to use a local prior before it's assigned a value, whether an uninitialized local variables is given an initial value is an implementation detail. Apr 6, 2015 at 12:50
  • 1
    Please see my most recent edit. I blame insufficient coffee on a Monday morning.
    – user22815
    Apr 6, 2015 at 12:59
4

What is the difference between a variable assigned to null and others not assigned in memory?

There is no such thing as an unassigned variable in Java. Class data members that don't have an explicit assignment are assigned the default value for the type, null for an object, or something akin to 0 for primitive types.

Local variables live on the stack. (Non-primitive locals such as MyType foo also live on the stack, as references.) The stack allocation is simple. If a block contains declarations for local variables, the space needed by those local variables is reserved on the stack. Whether values are assigned to those local variables on adjusting the stack to accommodate those local variables is irrelevant.

The reason it doesn't matter is whether local variables are or are not assigned a value at the time execution enters the block is twofold. One reason is that the size needed doesn't change. Primitives have a fixed size, and non-primitives are actually references. (The referenced object lives on the heap rather than the stack.) The second reason is that using a local variable that hasn't been assigned a value is a compilation error. This leaves it up to the Java runtime whether to give some value (not necessarily the default) to a declared but unassigned local variable.

4
  • Somewhere in your answer is the explanation to this: When you declare a variable without initializing it to null, then initialize it inside a if-then block, the compiler tells you that the variable maybe uninitialized ahead in the code if the then block is not executed. If you initialize it to null the code compiles. Why is that given that " a reference not explicitly assigned a value will have the value null" ? But it's still not clear enough for me. Could you explain it in other words? Apr 6, 2015 at 12:42
  • 2
    Local variables do not need to be given an initial value. They need to be assigned a value prior to initial use. Whether the memory associated with that variable is given an explicit initial value, even in the case of a declaration with no assignment, is an implementation detail. The memory exists (that's how stacks work), but that memory space could be left filled with whatever happened to be in that memory prior to adjusting the stack. Apr 6, 2015 at 12:54
  • @user61852 - That a reference not explicitly assigned a value will have the value null is true for class members, but not necessarily for local variables. If you are compiling your code with debug enabled, the compiler will almost certainly initialized your uninitialized non-primitive local variables to null. This greatly simplifies the development of the Java debugger. But what if you compile with debug disabled? Now that initialization is unnecessary extra work. What's in that memory is irrelevant because it is known that the memory will contain a valid value on first use. Apr 6, 2015 at 13:12
  • From a bytecode perspective, local variables are allocated on the stack. The JITter, however, may decide decide that a particular stack entry shouldn't actually be stored on the stack, but stores to and loads from that entry should be directed at a particular CPU register. Further, if the JITter determines that once execution reaches a certain point there's no way a stack entry will be read without having been rewritten, it may reassign that entry's associated register for some other purpose.
    – supercat
    Apr 6, 2015 at 15:32
1

First, there is really no need to worry about the space used by local variables. In one line I can allocate an array of 100,000 integers which will take more space than all the local variables that you are ever going to use.

Second, your code is compiled by a compiler which is likely to be clever. If your variable isn't initialized, it isn't used (because the compiler doesn't allow to use uninitialized variables). But if you initialize it to nil, it still isn't used! The compiler will easily figure out that it isn't used and not actually use space for the variable at all. Even if it is used, the compiler will easily figure out that the value is nil, and use nil instead of the the variable.

But third, this is all micro-optimisations that are not going to help you optimise a program in any way. You are trying to save four or eight bytes. Concentrate on saving megabytes if you want to save anything.

And last, while some people claim variables should always be initialised, that's not true in Java. You should only ever set a variable to a meaningful value. Let's say you want to set a variable to the name of a person, and you forget to do this in one code path. If you blindly initialize the variable to nil, the compiler can't tell you. Without the initialisation, the compiler can and will tell you about your mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.