Search code examples
javaclassobjectmemory

What happens when an object is only defined?


I was wondering what happens at memory level when an object in defined, but not initialized.

For example:

public class MainClass {
 public static void main (String[] args){
  Object foo;
 }
}

Is foo pointing to a memory space? Does this behaviour change between different programming languages?

Thanks in advance.

Edit: I know the object will point to null when used, but I am interested to know what happens just after the object has been defined, and not instantiated yet. Is there a reference to the memory in this case?


Solution

  • I was wondering what happens at memory level when an object in defined, but not initialized.

    Lets assume that we are talking about Java here.

    First I must correct your incorrect description. (For reasons that will become apparent ...)

    This is not defining an object. Rather, it is declaring a variable. The identifier foo denotes a variable. Since the type of the variable is (in this case) Object which is a reference type, the variable may contain either a reference to a Java object or null.

    Is foo pointing to a memory space?

    The answer is slightly complicated.

    • If the variable is initialized, it will either point to some object or it will contain null.

    • If the variable is NOT initialized, then it depends on what type of variablle we are talking about:

      • For a field of a class (static or instance), a variable that is not explicitly initialized is default initialized to null.

      • For a variable that is a parameter or a catch variable, the Java language semantics ensure that the variable is always initialized ... so this is moot.

      • For a local variable, the JLS doesn't say what it contains before a value is assigned to it. You could say that the value is indeterminate. However the JLS (and at runtime, the JVM's classfile verifier) ensure that a program cannot use a local variable that is in an indeterminate state. (It is a compilation error in Java code to read a variable that has not been definitely assigned.) So it really makes no difference what the variable actually contains.

    Note that in pure Java1 it is not possible to access a variable that contains a value that it wasn't set by either assignment or initialization. The Java Language Specification doesn't allow it and neither does the JVM Specification. A variable can never be observed to contain a random memory address.

    Does this behavior change between different programming languages?

    Err ... yes. For example, in C and C++, a program may use the value of a pointer variable that has not been initialized. The behavior that ensues is unspecified.


    1 - If you use native code or Unsafe, it is possible for the code to corrupt a variable to contain anything. But don't do this deliberately as this is liable to hard crash the JVM. Native code and Unsafe means not pure Java.