Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local Variables, Object references and it's memory allocation

I have the following block of code:

class Student{

int age;               //instance variable
String name;     //instance variable

public Student()
 {
    this.age = 0;
    name = "Anonymous";
 }
public Student(int Age, String Name)
 {
    this. age = Age;
    setName(Name);
 }
public void setName(String Name)
 {
    this.name = Name;
 }
}

public class Main{
public static void main(String[] args) {
        Student s;                           //local variable
        s = new Student(23,"Jonh");
        int noStudents = 1;          //local variable
 }
}

My question is related to what are local variables, instance variables in order to know where they are allocated, wether in HEAP or STACK memory. In the default constructor it seems to exist only one Local variable, which the one created by the 'this' keyword, but howcome ' name = "Anonymous";' is not considered to be a local variable? It's pf the Object type, but those can be local varibles too, correct? By the way can you give an example of an object created/instantiatedwith the default constructor? Thank you!

like image 681
csbl Avatar asked May 18 '12 18:05

csbl


1 Answers

In short, names of any kind only store references, they do not store objects directly.

A name that is completely constrained to a block of code has allocated storage for the reference, on the stack frame, which is on a Stack that is private to the Thread.

A name that is a member of a class has allocated storage for the reference in the heap, within the Object that represents the instance of that class.

A name that is a static member of a class has allocated storage for the reference in the heap, within the Object that represents the instance of the Class Object of that class.

All objects live on the heap; however, references to them may live within other objects on the heap, or within reference placeholders on the stack.

All primitive data types are stored where the reference would have been stored.

class Student {

  int age;         // value stored on heap within instance of Student
  String name;     // reference stored on heap within instance of Student

  public Student() {
    this.age = 0;
    name = "Anonymous";
  }

  public Student(int Age, String Name) {
    this.age = Age;
    setName(Name);
  }

  public void setName(String Name) {
    this.name = Name;
  }

}

public class Main {
  public static void main(String[] args) {
        Student s;                    // reference reserved on stack
        s = new Student(23, "John");  // reference stored on stack, object allocated on heap
        int noStudents = 1;           // value stored on stack
  }
}
like image 147
Edwin Buck Avatar answered Oct 03 '22 01:10

Edwin Buck