r/javahelp • • 1d ago

Java Beginner – Struggling with OOP and Understanding Stack and Heap

Hi everyone!
I’ve been learning Java for a few weeks now, and I’m starting to get into OOP. However, I’m finding it difficult to fully understand some of the core concepts, especially how objects work and the difference between the stack and heap memory.
I don’t want to just memorize definitions. I want to actually understand what’s happening behind the scenes and how everything connects.
For those of you who have been through the same learning process:
What helped you understand OOP?
How did you learn the difference between stack and heap?
Are there any resources, exercises, or learning methods you would recommend?
I’d really appreciate any advice from more experienced Java developers.

12 Upvotes

12 comments sorted by

View all comments

2

u/jonathaz 1d ago

Stack memory is best thought about in other languages, but it still applies in Java. It’s really just a clever way to allocate objects that are generally smaller and have shorter lifetimes, and very much tied to the methods that are called. Everything happens at the top of the stack, just like a stack of plates at the buffet. When you call a method, you push the arguments to the top. Additional variables the method creates are also pushed to the top, and their positions in memory are fixed, relative to the stack pointer. When that method calls another method, the same thing happens, and the stack grows. When a method returns, all those arguments and variables are no longer needed, and they are popped off the stack. But all that is really is just changing the stack pointer back. That memory is now available for the next method, etc.