int[] arr = new int[3]; int top = -1; // Push 10 arr[++top] = 10; // Push 20 arr[++top] = 20; // Pop int popped = arr[top--]; // Push 30 arr[++top] = 30; // Print stack elements from bottom to top for (int i = 0; i <= top; i++) { System.out.print(arr[i] + " "); }
Remember how push and pop change the top index.
The array acts like a stack with 'top' tracking the last element. After pushing 10 and 20, popping removes 20, then pushing 30 adds it on top. So elements are 10 and 30.
Think about safety and control over data.
Stack abstraction hides the internal array and only allows push/pop at the top, preventing accidental changes to other elements.
int[] stack = new int[2]; int top = -1; stack[++top] = 5; stack[++top] = 10; stack[++top] = 15; // What happens here?
Check the array size and index used.
The array size is 2, but the code tries to insert at index 2 (third element), which is out of bounds.
class Stack { private int[] arr = new int[3]; private int top = -1; public void push(int x) { if (top == arr.length - 1) return; arr[++top] = x; } public int pop() { if (top == -1) return -1; return arr[top--]; } public void printStack() { for (int i = 0; i <= top; i++) { System.out.print(arr[i] + " "); } } } Stack s = new Stack(); s.push(1); s.push(2); s.push(3); s.push(4); int p = s.pop(); s.printStack();
Notice the stack size limit and pop effect.
The stack size is 3, so push(4) is ignored. Pop removes 3. Remaining elements are 1 and 2.
Think about encapsulation and control.
Stack abstraction encapsulates the data and exposes only push/pop, preventing accidental misuse and allowing internal changes without affecting users.
