Applications of Stacks#
Where are stacks used? Stacks are very common in software including browsers, word processors and even just the running process for programs that include functions.
Directions Feature of Browser#
Often two stacks are used: one for holding the webpages for moving backward and one for those when moving forward. Each time a new webpage is visited, the previous site is stacked onto the “backward” stack for the back button. When the back button is clicked, the current webpage is pushed onto the “forward” stack, and the top of the “backward” stack is popped leading us to the previous page. If we then click the forward button, the current webpage is again pushed and the top of the “forward” stack is popped.
Handling Undo & Backtracking#
Word processors stack commands, so when you want to undo something this happens by reversing the action at the top of the stack. Many games do a progression between rooms, and again this is handled with a stack. Solving a maze can be done with a stack: whenever you reach a junction, a point where there is a choice, all the options may be placed onto a stack. Likewise, the solution to the maze may be created via a stack.
Running Methods in Java#
Have you ever wondered how it is that you can use the same variable names in different methods, and they are different variables?
The Java Virtual Machine places all variables onto a stack in memory during run-time. When a method is called, its variables are pushed onto the stack, along with other information such as the return value and the location where to continue executing once the method is done. This stack is a special stack, the system stack, and is used for all method calls and returns. This stack will contain a bunch of stack frames, where each frame contains the local variables, return address, and return value of a particular method.
Let’s look at an example:
1. public static void main(String[] args) {
2. int i = 5;
3. foo(i);
4. }
5. public void foo(int j) {
6. int i;
7. i = j + 1;
8. goo(i);
9. }
10. public void goo(int m){
11. }