public class Main {
public static void main(String[] args) {
int x = foo();
System.out.println(x);
}
static int foo() {
return 10;
}
} │ │
│ ... │ ← свободное место
│ │
├────────────┤
│ main() │ ← вершина стека
│ args │
│ x = ? │
└────────────┘ │ │
│ ... │ ← свободное место
│ │
├────────────┤
│ foo() │ ← вершина стека
├────────────┤
│ main() │
│ args │
│ x = ? │
└────────────┘ │ │
│ ... │ ← свободное место
│ │
├────────────┤
│ main() │ ← вершина стека
│ args │
│ x = 10 │
└────────────┘ static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
} factorial(3)
↓
factorial(2)
↓
factorial(1)
↓
factorial(0) │ │
│ ... │
│ │
├─────────────────┤
│ factorial(0) │ ← вершина стека
├─────────────────┤
│ factorial(1) │
├─────────────────┤
│ factorial(2) │
├─────────────────┤
│ factorial(3) │ ← вызван первым
└─────────────────┘ factorial(0) возвращает 1
factorial(1) возвращает 1 * 1 = 1
factorial(2) возвращает 2 * 1 = 2
factorial(3) возвращает 3 * 2 = 6 class Hello {
public static void main(String[] args) {
sayHello();
}
private static void sayHello() {
System.out.println("Hello");
sayHello();
}
} ...
Hello
Hello
Hello
Hello
Exception in thread "main" java.lang.StackOverflowError
...
at Hello.sayHello(Hello.java:8)
at Hello.sayHello(Hello.java:9)
at Hello.sayHello(Hello.java:9)
at Hello.sayHello(Hello.java:9)
... class Example {
private Example example = new Example();
} class A {
private B b = new B();
}
class B {
private A a = new A();
}
Помимо рассмотренных ранее, куча имеет следующие ключевые особенности:
class Person {
int id;
String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
}
public class PersonBuilder {
public static void main(String[] args) {
int id = 23;
String name = "John";
Person person = null;
person = buildPerson(id, name);
}
private static Person buildPerson(int id, String name) {
return new Person(id, name);
}
}