-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectMemoryAllocation.java
More file actions
49 lines (37 loc) · 1.33 KB
/
Copy pathObjectMemoryAllocation.java
File metadata and controls
49 lines (37 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package Phase1_CoreLanguage.Extra;
/**
*In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap.
* In C++, when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.
* <p>
*
* In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new().
* So the object is always allocated memory on heap (See this for more details).
* <p>
*
* If we create a class variable then it'll not allocate the memory in memory Heap.
* When we use new keyWord then then it'll allocate the memory in memory Heap.
*/
public class ObjectMemoryAllocation {
public static void main(String[] args)
{
Test t;
// Error here because t
// is not initialzed
// t.show(); //TODO UNCOMMENT FOR TEST
//Error
//java: variable t might not have been initialized
// all objects are dynamically
// allocated
Test t2 = new Test();
t2.show(); // No error
//OUTPUT
//Test::show() called
}
}
class Test {
// class contents
void show()
{
System.out.println("Test::show() called");
}
}