Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
Now Reading
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Memory in Java can be categorized into two separate sections; heap memory and stack memory. The stack memory is where objects are dispensed and deallocated dynamically while executing a program.
It is overseen by the Java Virtual Machine (JVM), leaving a huge and adaptable storage space for objects. Stack memory, however, stores local variables and method calls. It is important to learn about heap memory and stack memory in Java with examples, their use cases, and their differences in managing memory and preventing memory leaks and stack overflows efficiently.
This tutorial is a detailed guide to understanding what is heap memory and stack memory in Java. You will gain an in-depth understanding of the same with examples illustrating the use cases of both these categories, their advantages, and their disadvantages.
Stack memory in Java refers to a part of the memory used to store method calls and local variables. It operates in a LIFO (last-in-first-out) manner, where the items added most recently are accessed first. It is a limited and efficient memory space automatically managed by the JVM, making it suitable for handling method invocations and storing temporary data during program execution.
Here is an example of stack memory usage in Java:
public class upGrad {
public static void main(String[] args) {
int a = 5;
int b = 10;
int sum = calculateSum(a, b);
System.out.println("Sum: " + sum);
}
public static int calculateSum(int x, int y) {
int result = x + y;
return result;
}
}
In this example, the stack memory is used to store the method frames and local variables for the main method and the calculateSum method. As each method is called, a new stack frame is created, and when a method finishes its execution, its stack frame is removed from the stack. This allows for efficient memory management and helps in organizing the execution of methods and handling local variables.
The variables a and b are declared and initialized with values 5 and 10, respectively. These variables are stored in the stack frame of the main method. The calculateSum method is called, passing the values of a and b as arguments. A new stack frame is created for the calculateSum method.
Inside the calculateSum method, the parameters x and y are declared and assigned the values passed from the main method. These variables are stored in the stack frame of the calculateSum method. The variable result is declared and assigned the sum of x and y. This variable is also stored in the stack frame of the calculateSum method.
The result variable is returned to the main method. The stack frame of the calculateSum method is removed from the stack. The value returned from the calculateSum method is stored in the variable sum in the stack frame of the main method. The value of sum is printed to the console.
In Java, a StackOverflowError exception occurs when the stack memory, which is used to track method calls and store local variables, exceeds its limit. This typically happens when there is a recursive method call without a proper base case, causing an infinite loop and exhausting the available stack space.
When a StackOverflowError occurs, it indicates that the program's call stack has overflowed, and the JVM cannot allocate additional memory for method invocations.
Example:
In this example, when the main method is executed, it calls the recursiveMethod. The recursiveMethod is designed to call itself endlessly without any termination condition. As a result, the call stack keeps growing until it exceeds its maximum limit, throwing a StackOverflowError.
Heap memory in Java is a memory region for dynamic memory allocation. It is the runtime data area where objects are assigned and released during program execution.
JVM manages it and serves as the primary repository for many application data, encompassing objects, arrays, and class instances. Heap memory assigns memory to objects upon creation and reclaims memory through garbage collection when objects become obsolete.
public class HeapExample {
public static void main(String[] args) {
// Creating objects in the heap memory
Person person1 = new Person("Manisha", 26);
Person person2 = new Person("Aron", 26);
// Modifying object properties
person1.setAge(27);
person2.setName("Aritra");
// Printing object details
System.out.println(person1.getName() + " is " + person1.getAge() + " years old.");
System.out.println(person2.getName() + " is " + person2.getAge() + " years old.");
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
In this example, the heap memory is allocated for the objects created from the Person class. The objects persist in memory until they are no longer referenced, at which point the Java garbage collector deallocates the memory occupied by those objects. The heap memory allows for dynamic memory allocation and deallocation, providing flexibility for managing objects and data structures in Java programs.
When the main method is executed, two objects of the Person class, person1 and person2, are created using the new keyword. The memory for these objects is allocated on the heap. The constructor of the Person class is called for each object, initializing the name and age instance variables. The properties of the objects are modified using setter methods, changing the values stored in the heap memory. The getter (getAge and getName) methods retrieve the values from the objects in the heap memory. The object details, including the names and ages, are printed on the console.
An OutOfMemoryError occurs when the JVM cannot allocate any memory for a memory allocation request. This error occurs when the heap memory of the JVM is fully exhausted, resulting in the inability to allocate any additional memory for objects.
To address an OutOfMemoryError indicates that the application may necessitate optimizations or adjustments to the memory settings because it has reached its maximum memory capacity.
In this example, we have a List<Integer> called numbers. We attempt to continuously add elements with the value of 1 to the list inside an infinite loop. Eventually, the memory allocated for the heap will be exhausted, resulting in an OutOfMemoryError.
import java.util.ArrayList;
import java.util.List;
public class upGrad {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
try {
while (true) {
numbers.add(1);
}
} catch (OutOfMemoryError e) {
System.out.println("Out of memory!");
}
}
}
Stack Memory | Heap Memory |
Used for storing local variables and method calls | Used for dynamically allocating and deallocating objects |
Operates in a last-in-first-out (LIFO) manner | Objects are allocated and deallocated dynamically |
Limited in size | Provides a larger and more flexible storage space |
Managed by the JVM automatically | Managed by the JVM through garbage collection |
Faster access and deallocation | Slower access and deallocation |
Stores primitive types and references | Stores objects, arrays, and class instances |
Memory allocation and deallocation are automatic | Memory allocation and deallocation must be managed |
Memory usage is determined at compile-time | Memory usage is determined at runtime |
Memory space is smaller | Memory space is larger |
Typically used for method invocations | Typically used for dynamically created objects |
Some of the advantages of using Stack Memory in Java have been elucidated below:-
There are a few downsides to using Stack Memory in Java. They are:-
Some key benefits of using Heap Memory in Java are:-
Here are some disadvantages of using Heap Memory in Java:-
Heap memory and stack memory are two essential components of memory management in Java. Heap memory provides flexible storage space for dynamically allocated objects, while stack memory efficiently handles method invocations and local variables. Understanding these memory concepts is crucial for developing efficient and optimized Java applications.
To learn more about these important Java concepts, consider taking up a course in upGrad to enhance your knowledge and skills in the fundamental and advanced concepts of Java programming.
1. What is the key difference between heap memory and stack memory in Java?
The main difference between heap and stack memory in Java is that heap memory is used for dynamically allocating objects, while stack memory is used for storing local variables and method calls.
2, How is stack allocation different from heap allocation in Java?
Stack allocation refers to the automatic memory management of method invocations and local variables. On the other hand, heap allocation refers to the dynamic allocation and deallocation of objects.
3. Is heap memory allocated on the hard disk or in the RAM?
In Java, heap memory is allocated in the RAM (Random Access Memory) and not on the hard disk.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...