Skip to content

Commit c727758

Browse files
[Edit] Java stack (#6575)
* Update stack.md * Update stack.md * Add files via upload * fixed some content and also fixed lint and format * Update stack.md changed images * Add files via upload ---------
1 parent cadbd2c commit c727758

File tree

3 files changed

+70
-42
lines changed

3 files changed

+70
-42
lines changed

content/java/concepts/stack/stack.md

Lines changed: 70 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,31 @@
11
---
22
Title: 'Stack'
3-
Description: 'A stack is a linear data structure where items are added and removed from the top in a last-in, first-out (LIFO) order.'
3+
Description: 'Represents a last-in, first-out data structure for storing objects.'
44
Subjects:
55
- 'Code Foundations'
66
- 'Computer Science'
77
Tags:
88
- 'Collections'
9-
- 'Stack'
109
- 'Data Structures'
10+
- 'Stack'
1111
CatalogContent:
1212
- 'learn-java'
1313
- 'paths/computer-science'
1414
---
1515

16-
A **`Stack`** is a linear data structure that adds and removes items from the top in a last-in, first-out (LIFO) order. The `Stack` class comes from the `java.util` package and extends the legacy `Vector` class.
16+
A **stack** in Java represents a _last-in, first-out_ (LIFO) data structure for storing objects. It is implemented as the `Stack` class within the `java.util` package and extends the `Vector` class. A stack allows operations such as pushing items to the top, popping items off the top, and peeking at the top item without removing it.
17+
18+
Stacks are commonly used in programming problems involving recursion, expression evaluation, undo functionality, and backtracking algorithms.
19+
20+
A common use of stacks is implementing the _undo_ feature in text editors. Each action a user takes (e.g., typing a character) is pushed onto a stack. When the undo command is triggered, the most recent action is popped from the stack and reversed.
1721

18-
An opposite data structure is the [`Queue`](https://www.codecademy.com/resources/docs/java/queue) interface, which follows the first-in, first-out (FIFO) order. The `Stack` and `Queue` concepts can be observed in everyday life (e.g., waiting in a line of people to purchase something or washing a stack of dishes from top to bottom).
22+
To use the `Stack` class, it must first be imported using:
23+
24+
```java
25+
import java.util.Stack;
26+
```
1927

20-
Since Java 1.6, there is a more recent implementation of LIFO stack operations, the `Deque` interface. As stated in the JDK documentation, `Deque` interface should be used in preference to the legacy `Stack` class. Whenever a `Deque` is used as a `Stack`, elements are pushed and popped from the beginning of the `Deque`. The table below shows the equivalent methods between `Stack` and `Deque`:
28+
Since Java 1.6, the [`Deque`](https://www.codecademy.com/resources/docs/java/deque) interface has provided a more modern and efficient way to implement LIFO stack operations. According to the JDK documentation, `Deque` should be used in preference to the legacy `Stack` class.
2129

2230
| `Stack` method | Equivalent `Deque` method |
2331
| :------------: | :-----------------------: |
@@ -28,61 +36,81 @@ Since Java 1.6, there is a more recent implementation of LIFO stack operations,
2836
## Syntax
2937

3038
```pseudo
31-
import java.util.Stack;
32-
33-
Stack<DataType> s = new Stack<>();
39+
Stack<Type> stackName = new Stack<>();
3440
```
3541

36-
Where `DataType` is the [data type](https://www.codecademy.com/resources/docs/java/data-types) to be stored in the stack.
42+
**Parameters:**
43+
44+
- `Type`: The data type of elements stored in the stack (e.g., `Integer`, `String`).
45+
- `stackName`: The variable name of the `Stack` object.
3746

38-
**Note:** Unlike `Queue`, `Stack` is a concrete class and not an interface.
47+
> **Note:** Java stacks are generic, meaning they can store any object type specified in angle brackets.
3948
40-
## Methods
49+
## Common Stack Methods
4150

4251
The `Stack` class provides the following methods:
4352

44-
- `.push(item)`: adds an item to the top of the `Stack`.
45-
- `.pop()`: removes and returns the object at the top of the `Stack`, throwing an exception when the `Stack` is empty.
46-
- `.peek()`: returns the (top) of the `Stack` without removing it, and throws an exception when the `Stack` is empty.
47-
- `.empty()`: returns `true` if the `Stack` contains no items or `false`, otherwise.
48-
- `.search(item)`: returns the distance the `item` is from the top of the `Stack`, starting from `1`, or `-1` is if `item` is not in the `Stack`.
53+
- `.push(item)`: Adds an item to the top of the stack.
54+
- `.pop()`: Removes and returns the item from the top of the stack.
55+
- `.peek()`: Returns the item at the top without removing it.
56+
- `.empty()`: Returns `true` if the stack is empty.
57+
- `.search(item)`: Returns the 1-based position from the top of the stack if found; otherwise, returns -1.
4958

50-
## Example
59+
![Diagram showing stack structure where push adds an element to the top and pop removes the top element](https://raw.githubusercontent.com/Codecademy/docs/main/media/java-stack-push-pop-diagram1.png)
5160

52-
The following example demonstrates the `Stack` class:
61+
## Example: Basic Stack Operations
62+
63+
The following example demonstrates how to use common stack methods such as `.push()`, `.pop()`, `.peek()`, `.empty()`, and `.search()`:
5364

5465
```java
55-
// Main.java
5666
import java.util.Stack;
57-
import java.util.Arrays;
5867

59-
public class Main {
68+
public class StackExample {
6069
public static void main(String[] args) {
6170
Stack<String> books = new Stack<>();
62-
System.out.println(books.isEmpty());
63-
books.push("Effective Java");
64-
books.push("Head First Java");
65-
books.push("Thinking in Java");
66-
System.out.println(books.size());
67-
System.out.println(books.search("Effective Java"));
68-
System.out.println(books.search("Java for dummies"));
69-
System.out.println(books.peek());
70-
System.out.println(books.pop());
71-
System.out.println(books.size());
72-
System.out.println(Arrays.toString(books.toArray()));
73-
}
71+
72+
// Push items onto the stack
73+
books.push("Java");
74+
books.push("Python");
75+
books.push("C++");
76+
77+
// Peek at the top item
78+
System.out.println("Top item: " + books.peek()); // C++
79+
80+
// Pop the top item
81+
books.pop();
82+
83+
// Check if stack is empty
84+
System.out.println("Is stack empty? " + books.empty());
85+
86+
// Search for an item
87+
System.out.println("Position of Java: " + books.search("Java"));
88+
}
7489
}
7590
```
7691

77-
This will output the following:
92+
This example will result in the following output:
7893

7994
```shell
80-
true
81-
3
82-
3
83-
-1
84-
Thinking in Java
85-
Thinking in Java
86-
2
87-
[Effective Java, Head First Java]
95+
Top item: C++
96+
Is stack empty? false
97+
Position of Java: 2
8898
```
99+
100+
## Frequently Asked Questions
101+
102+
### 1. What is a stack in Java?
103+
104+
A stack is a linear data structure that follows the _last-in, first-out_ (LIFO) principle. In Java, it is represented by the `Stack` class in the `java.util` package.
105+
106+
### 2. How do you implement a stack in Java?
107+
108+
A stack can be implemented using the built-in `Stack` class or manually using [arrays](https://www.codecademy.com/resources/docs/java/arrays) or linked lists. The simplest approach is:
109+
110+
```java
111+
Stack<Integer> stack = new Stack<>();
112+
```
113+
114+
### 3. What is the difference between stack and queue in Java?
115+
116+
A stack uses LIFO (last-in, first-out) ordering, while a [queue](https://www.codecademy.com/resources/docs/java/queue) uses FIFO (first-in, first-out). This means stacks remove the most recently added element, while queues remove the oldest one.

media/java-stack-push-pop-diagram.png

1.27 MB
Loading
1.2 MB
Loading

0 commit comments

Comments
 (0)