none
How Memory is assigned to following two lines RRS feed

  • Question

  • ClassA obj = null;

    obj = new ClassA();

    Is in first line object will be created on stack.

    Monday, November 21, 2011 12:29 PM

Answers

  • Classes are "reference types". That means that every time you say:

    ClassA obj;

    you're declaring a variable that stores a reference to an instance (object) of ClassA. What's a reference? It is the memory address of the object. The size in bytes of such a variable is always 4 bytes (or 8 bytes on 64-bit CPUs)

    If you do

    obj = null;

    you're basically store address 0 in the variable obj.

    When you do:

    obj = new ClassA();

    new will allocate some heap memory to store the object and will return the allocated memory address. This address is stored in the variable obj.

     

    • Marked as answer by Paul Zhou Tuesday, November 29, 2011 5:39 AM
    Monday, November 21, 2011 12:53 PM
    Moderator

All replies

  • Hmm, the first line doesn't create any object, it simply assigns null to the variable obj. Of course, the variable itself is "created" on the stack, but a variable is not an object, it's only a reference to the object.
    Monday, November 21, 2011 12:40 PM
    Moderator
  • Thanks Mike

    But can you please explain your last words " but a variable is not an object, it's only a reference to the object."

    Sorry I am weak in memory management.

    Monday, November 21, 2011 12:42 PM
  • Classes are "reference types". That means that every time you say:

    ClassA obj;

    you're declaring a variable that stores a reference to an instance (object) of ClassA. What's a reference? It is the memory address of the object. The size in bytes of such a variable is always 4 bytes (or 8 bytes on 64-bit CPUs)

    If you do

    obj = null;

    you're basically store address 0 in the variable obj.

    When you do:

    obj = new ClassA();

    new will allocate some heap memory to store the object and will return the allocated memory address. This address is stored in the variable obj.

     

    • Marked as answer by Paul Zhou Tuesday, November 29, 2011 5:39 AM
    Monday, November 21, 2011 12:53 PM
    Moderator