r/javahelp • • 15h 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.

8 Upvotes

11 comments sorted by

•

u/AutoModerator 15h ago

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

4

u/Jamarlie 12h ago

Two tips here from someone who has also taught a few courses on basic programming:

  1. If you are just starting out to program in general, ignore OOP as far as possible for now. First get the basics down. Otherwise you are effectively asking how to drive an F1 car if you've never even driven a go-kart before. Later understanding things like inheritance, polymorphism and typical design principles will make more sense. In the beginning they usually just needlessly frustrate and confuse beginners.
  2. Same with stack vs. heap. For Java, you generally let the JVM handle all of these allocations and not worry about it all too much. The difference between stack and heap is much more important to understand for languages like C/C++ or Rust. In Java you can blissfully ignore this for now. If you want an explanation: This is just the difference between regions that your program knows ahead of time vs. regions that your program needs to dynamically fetch during execution.

If I have an array of length 3, then I know at compile-time that my array will be 3. So that goes on the stack. If I ask the user for input, I have no way to know how much input the user gives me until he has given me his input. That is a dynamic allocation that belongs on the heap. That's all you really need to know for now, I feel like getting into the thick of it will only hurt you at this stage.

2

u/Reasonable-Pay-8771 10h ago

^^ This ^^

Unless you're getting into the JVM and compiler and the byte-code and stuff, Java really hides all this from you (viz. stack vs heap).

OOP is a problematic abstraction because it abstracts away the details of a computer by making it look like a computer. Like if you watch old Alan Kay videos you get the idea. An object = data + functions that operate on that data (which basically is just what a computer already is). And then you have add all the doodads on to get actual abstracting power: inheritance, polymorphism, modules (which kinda turn out to be maybe what objects ought to have been from the beginning).

I'd recommend watching at least one old Alan Key keynote or something, and then a handful of prefaces from some 80s OO books and that should give you a pretty good grounding. But then, every OO language or implementation is going to have its own special ideas of how it all should work. So if you're going for Java, then don't dwell too long on Alan Kay or any other non-Java-focused OO description because it may or may not be relevant to how Java does it or how you're likely to do it in Java.

1

u/Jamarlie 2h ago

I second this as well. I know this is something people here do not like to hear, but Java is a bad first programming language in general. It was never designed to be a good beginner language either. You effectively have the entire concept of classes bolted onto every core principle you work with so you will always need to do more. And while I specifically recommend it here in this situation, entirely ignoring the Stack vs. Heap is also not really the most ideal construct. It also has some amount of impact within the JVM, though to a much lesser extend. The parts where it does matter can come back to bite you though, like constant object creation with an Integer vs primitive int array.

That's why I personally do not feel like recommending higher level languages like Java to beginners is worthwhile. Beginners need to focus on learning core concepts and fundamental ideas. You don't teach a 1st grader the basics of addition by letting them do point additions on elliptic curves either. This feels very analogous to that.

2

u/jonathaz 9h 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.

2

u/Lost-Quantity1282 3h ago

Use the visual debugger in IntelliJ IDEA. Set a breakpoint in your main method and run it in debug mode. Watch the variables panel closely as you step through code with primitive types versus objects. You will literally see the references in the local stack frame point to different addresses on the heap. This shows you exactly how memory allocation works better than any definition ever could

1

u/Kautsu-Gamer 14h ago

Objects are one simple and one complex thing:

  • Objects are data (fields) and functions (methods) packed together.
  • Objects are polymorphic. This is the hard part.

Polymorphism means the actual class and the observed class or interface may differ.

  • The observed class gives methods of the object from outside.
  • The actual class does define the actual implementation.

    • The actual implementation happens with the actual class by default.
    • If the actual class does not have implementation, the super class implementation is used.
    • The call of super transfers the implementation to a super class or super interface.

1

u/Duck_Devs 14h ago

The stack is a very restrictive segment of memory. Local variables are the only things that are stored there. While your variables can include object references, the actual object data is stored on the heap. Along with objects, the heap also stores arrays, as well as any primitive values or object references held by objects and arrays.

There also exists “off-heap memory”, but that’s not something a beginner should worry much about.

1

u/alex_dimas 12h ago

I found the first few lectures of CS61B from Berkeley on YouTube to be informative on these concepts.

1

u/Agawell 10h ago

What helped me understand OO? Reading Grady Booch’s book on object oriented design over 30 years ago

Look around you - everything is an object, an instance of a class

Think about a mug - what properties does it have? What functions does it have? How does it relate to a cup? How does it relate to a bowl? What do all these things inherit properties and functions from (vessel, perhaps)

IMO it really helps to see things in this way before trying to understand more abstract classes

-1

u/AmiAmigo 14h ago

OOP is not intuitive at all.

How about you try first learning procedural PHP…and see how it translates to OOP PHP