Skip to content

Commit d8d3472

Browse files
authored
Add files via upload
1 parent 88f2b58 commit d8d3472

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
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.
2+
3+
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.
4+
5+
for example:
6+
7+
8+
class Test {
9+
10+
// class contents
11+
void show()
12+
{
13+
System.out.println("Test::show() called");
14+
}
15+
}
16+
17+
public class Main {
18+
19+
// Driver Code
20+
public static void main(String[] args)
21+
{
22+
Test t;
23+
24+
// Error here because t
25+
// is not initialzed
26+
t.show();
27+
}
28+
}
29+
30+
Correct Code:
31+
32+
33+
class Test {
34+
35+
// class contents
36+
void show()
37+
{
38+
System.out.println("Test::show() called");
39+
}
40+
}
41+
42+
public class Main {
43+
44+
// Driver Code
45+
public static void main(String[] args)
46+
{
47+
48+
// all objects are dynamically
49+
// allocated
50+
Test t = new Test();
51+
t.show(); // No error
52+
}
53+
}

0 commit comments

Comments
 (0)