What is the difference between the heap and the stack in memory management, and how does garbage collection work in Java?