0% found this document useful (0 votes)
378 views4 pages

Java Stack Interface Implementation

The document describes designing a Stack ADT using an interface in Java. The interface defines methods for push, pop, peek, display and isEmpty. An ArrayStack class implements this interface using an array to store elements. The interface and implementation provide exception handling. The main method tests the stack by taking user input of push, pop, peek, display or isEmpty operations and prints the results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
378 views4 pages

Java Stack Interface Implementation

The document describes designing a Stack ADT using an interface in Java. The interface defines methods for push, pop, peek, display and isEmpty. An ArrayStack class implements this interface using an array to store elements. The interface and implementation provide exception handling. The main method tests the stack by taking user input of push, pop, peek, display or isEmpty operations and prints the results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Stack ADT Interface
  • Java Class Implementation
  • Sample Program Execution

Stack ADT using Interface

Design a Java interface for ADT Stack. Implement this interface using an array. Provide
necessary exception handling in both the implementations.
The interface Stack must have the following method signatures.

 void push(int data)


 int pop()
 int peek()
 boolean isEmpty()
 void display()

Note: The display() method must print all the elements of the stack separated by a space in the
order of insertion if the stack is not empty. Else it throws necessary exception.

The query type can be any one of the following types.


1 - Push
2 - Pop
3 - Peek
4 - Display
5 - isEmpty

Example Input/Output 1:
Input:
19
1 10
1 20
1 30
1 40
4
2
4
2
3
4
1 50
4
5
2
2
2
2
3
5
Output:
Stack Elements: 10 20 30 40
Popped Element: 40
Stack Elements: 10 20 30
Popped Element: 30
Top Element: 20
Stack Elements: 10 20
Stack Elements: 10 20 50
FALSE
Popped Element: 50
Popped Element: 20
Popped Element: 10
Stack Underflow
Stack Empty
TRUE

Java
import [Link].*;
interface Stack {
void push(int data);
int pop();
int peek();
void display();
boolean isEmpty();
}
class ArrayStack implements Stack {
public int SIZE;
public int[] stack;
public int top = -1;
public ArrayStack(int SIZE) {
[Link] = SIZE;
[Link] = new int[SIZE];
}
@Override
public void push(int data) throws IndexOutOfBoundsException {
if (top + 1 < SIZE) {
stack[++top] = data;
} else {
throw new IndexOutOfBoundsException();
}
}
@Override
public int pop() throws EmptyStackException {
if (!isEmpty()) {
return stack[top--];
} else {
throw new EmptyStackException();
}
}
@Override
public int peek() throws EmptyStackException {
if (!isEmpty()) {
return stack[top];
} else {
throw new EmptyStackException();
}
}
@Override
public boolean isEmpty() {
return top == -1;
}
@Override
public void display() throws EmptyStackException {
if (!isEmpty()) {
for (int index = 0; index <= top; index++) {
[Link](stack[index] + " ");
}
} else {
throw new EmptyStackException();
}
}
}
public class Hello {
static final int SIZE = 100;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Stack stack = new ArrayStack(SIZE);
int N = [Link]();
for (int query = 1; query <= N; query++) {
int queryType = [Link]();
switch (queryType) {
case 1:
try {
[Link]([Link]());
} catch (Exception e) {
[Link]("Stack Overflow");
}
break;
case 2:
try {
[Link]("Popped Element: " + [Link]());
} catch (Exception e) {
[Link]("Stack Underflow");
}
break;
case 3:
try {
[Link]("Top Element: " + [Link]());
} catch (Exception e) {
[Link]("Stack Empty");
}
break;
case 4:
try {
[Link]("Stack Elements: ");
[Link]();
[Link]();
} catch (Exception e) {
[Link]("Stack Empty");
}
break;
case 5:
if ([Link]()) {
[Link]("TRUE");
} else {
[Link]("FALSE");
}
}
}
}
}

Common questions

Powered by AI

When implementing the `pop()` method in ArrayStack, it is critical to check if the stack is empty (i.e., `isEmpty()` method) before attempting to remove an element. This prevents `EmptyStackException`, which occurs if one tries to pop from an empty stack. Proper exception handling around `pop()` operations is essential for robust error management, ensuring that operations do not fail silently or crash the program .

The ArrayStack class handles exceptions in the following ways: - In `push(int data)`, an `IndexOutOfBoundsException` is thrown if the stack is full (no capacity to add more elements). - In `pop()` and `peek()`, an `EmptyStackException` is thrown if the stack is empty, as there would be no elements to pop or peek. - In `display()`, an `EmptyStackException` is thrown if the stack is empty, since there are no elements to display .

The `isEmpty()` method returns TRUE when the stack contains no elements, i.e., when the variable `top` is -1. This state is reached during execution in the example after all elements are removed through `pop()` operations. Initially, after the input operations, multiple elements are pushed onto the stack. As `pop()` is repeatedly called, each element is removed one by one, incrementally leaving fewer elements in the stack until all are eventually removed, reaching an empty state .

Using an array for the Stack ADT implementation has several advantages: it allows for straightforward, index-based access which is usually efficient in terms of speed due to constant-time access (`O(1)` complexity). However, it's limited by the initial size allocation (fixed capacity), which can lead to `Stack Overflow` if exceeded. This implementation does not dynamically resize, which can be a drawback when the number of elements is unpredictable. This design choice favors static space management over dynamic flexibility .

Initially, elements 10, 20, 30, and 40 are pushed onto the stack. When `display()` is called, it prints '10 20 30 40'. Subsequent `pop()` operations remove 40 and 30 from the stack, resulting in '10 20'. The `peek()` operation confirms that 20 is at the top. A `push()` operation adds 50, resulting in '10 20 50'. After several `pop()` operations, all elements (50, 20, 10) are removed, leaving the stack empty, confirmed by 'Stack Empty' message when attempting to `peek()` or `pop()` at the end .

The `display()` method in ArrayStack iterates through the array from index 0 to `top`, printing each element one by one. This iteration order ensures elements are displayed in the order they were pushed onto the stack (FIFO order with respect to the display, LIFO for stack operation). Therefore, the insertion order is preserved when showing elements .

In the provided example, the 'Stack Underflow' message is printed when attempting a `pop()` operation from an empty stack. This scenario would arise following the final round of `pop()` operations that exhaust the stack’s elements. Once empty, any further `pop()` attempts trigger an `EmptyStackException`, prompting the 'Stack Underflow' message. This clear notification aids in error diagnosis, quickly informing developers or users that the stack lacks elements for removal .

A `Stack Overflow` exception occurs when trying to `push()` a new element onto the stack when it is already at full capacity (`top + 1 = SIZE`). In the ArrayStack class, this condition is explicitly checked in the `push()` method. If the stack’s current top index plus one equals the stack's maximum size, an `IndexOutOfBoundsException` is thrown. This enforces the stack's fixed capacity and ensures that attempts to exceed this limit are managed appropriately by handling the exception .

The main method uses a `Scanner` to read user input for executing stack operations. It first reads an integer, `N`, indicating the number of subsequent operations. Then, it processes each operation based on an integer indicating the type of stack operation (`push`, `pop`, `peek`, `display`, `isEmpty`). This structured input processing allows dynamic interaction with the stack and illustrates flexibility in operation execution without hardcoded commands, thus enhancing interactivity and user control over stack behavior .

The Stack interface defines five key methods corresponding to standard stack operations: 1. `push(int data)` - adds an element to the top of the stack, corresponding to the push operation. 2. `pop()` - removes and returns the top element of the stack, corresponding to the pop operation. 3. `peek()` - returns the top element without removing it, allowing one to see the top element. 4. `isEmpty()` - checks if the stack is empty. 5. `display()` - prints all elements of the stack from bottom to top. These methods encapsulate the behavior expected from stack operations .

Stack ADT using Interface 
Design a Java interface for ADT Stack. Implement this interface using an array. Provide 
necessary
Output: 
Stack Elements: 10 20 30 40 
Popped Element: 40 
Stack Elements: 10 20 30 
Popped Element: 30 
Top Element: 20 
Stac
throw new EmptyStackException(); 
 
} 
 
} 
 
@Override 
 
public int peek() throws EmptyStackException { 
 
if (!isEmpty()
System.out.println("Stack Underflow"); 
 
} 
 
break; 
 
case 3: 
 
try { 
 
System.out.println("Top Element: " + stack.pee

You might also like