The stack is a linear data structure that follows the LIFO (last-in-last-out) principle. In the stack, an item inserts from the top and removes it from the top.

For example, in a box, books arranged in vertical order. The book at the top removes first and the book at the bottom removes last.

### Stack Comprises Four Operations

**Push:**Insert an item into the stack.**Pop**: Delete an item from the top of the stack.**Peek**: Returns top item of the stack**isEmpty**: Checks empty stack.

**Recommended:**Queue Data Structure Implementation in Java using an Array

Let’s create stack using an array

```
public class Stack {
int capacity;
int array[];
int top;
public Stack(int capacity) {
top = -1;
this.capacity = capacity;
array = new int[capacity];
}
boolean isEmpty() {
if(top < 0)
return true;
return false;
}
public int push(int item) {
if(top >= capacity - 1) {
System.out.println("The stack is overflow");
return 0;
}else {
this.array[++top] = item;
return item;
}
}
public int pop() {
if(top < 0) {
System.out.println("Stack is underflow");
return 0;
}else {
return this.array[top--];
}
}
public int peek() {
if(top > capacity - 1) {
System.out.println("The stack is overflow");
return 0;
}else if(top < 0){
System.out.println("The stack is underflow");
return 0;
}else {
return this.array[top];
}
}
public static void main(String[] args) {
Stack stack = new Stack(4);
System.out.println(stack.push(10) + " pushed into stack");
System.out.println(stack.push(20) + " pushed into stack");
System.out.println(stack.push(30) + " pushed into stack");
System.out.println(stack.push(40) + " pushed into stack");
System.out.println(stack.pop() + " popped from the stack");
System.out.println(stack.pop() + " popped from the stack");
System.out.println("Peek of the stack is " + stack.peek());
}
}
```

#### Output

```
10 pushed into stack
20 pushed into stack
30 pushed into stack
40 pushed into stack
40 popped from the stack
30 popped from the stack
Peek of the stack is 20
```

### Practical uses of stack in real world

- Find whether a string is a palindrome.
- Evaluating a given expression is valid or not.
- Used in recursion functions to implement algorithms like the
**tower of Hanoi**and**tree manipulations**. - Conversion of expressions ( prefix-infix-postfix)

### Conclusion

For interviews, the stack is an important data structure concept and understanding stack implementation will help in interviews.

**Recommended:**