Local variables, object references and memory allocation

I have the following 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 what are local variables, instance variables, in order to know where they are allocated in HEAP or STACK memory. In the default constructor, it seems that there is only one Local variable that the keyword 'this' creates, but howcome' name = "Anonymous"; not considered a local variable? This is an object type, but it can also be local variables, right? By the way, can you give an example of an object created / created using the default constructor? Thank!

+3
source share
2 answers

, , .

, , , , Thread.

, , , .

, , , .

; .

, .

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
  }
}
+8

var (int, double, boolean) . , "", , - ().

- var, , "Student s" ( , )

-1

All Articles