100% found this document useful (1 vote)
464 views5 pages

Stack Implementation Using Array in Java

This document discusses the implementation of a stack using an array in Java. It includes code to define a stack class with methods to push, pop and display elements. The main method runs a menu loop allowing the user to choose these stack operations and test the code. The code demonstrates basic stack operations of inserting at the top, removing from the top, and traversing the stack from top to bottom.

Uploaded by

Rohini Aravindan
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
100% found this document useful (1 vote)
464 views5 pages

Stack Implementation Using Array in Java

This document discusses the implementation of a stack using an array in Java. It includes code to define a stack class with methods to push, pop and display elements. The main method runs a menu loop allowing the user to choose these stack operations and test the code. The code demonstrates basic stack operations of inserting at the top, removing from the top, and traversing the stack from top to bottom.

Uploaded by

Rohini Aravindan
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

PRESIDENCY UNIVERSITY

Bengaluru, Karnataka
Computer Science & Engineering
School of Computer Science & Engineering

Subject: CSE2001 - Data Structures & Algorithms Semester: III


Lab Session : Ex 2 Date: 21/09/2023

Implementation of stack using array


import [Link].*;
public class stack_operations
{
static int value, top=-1,stack[]=new int[5],ch,i,choice;
static void push()
{
if(top<4)
{
Scanner sc1=new Scanner([Link]);
[Link]("Enter the value to be inserted");
value=[Link]();
top=top+1;
stack[top]=value;
}
else
{
[Link]("Stack Overflow-Stack is Full");
}
}
public void pop()
{
if(top==-1)
{
[Link]("Stack Underflow");

Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 1
}
else
{
[Link]("Element popped is:"+stack[top]);
top=top-1;
}
}

public void display()


{
if(top==-1)
{
[Link]("Stack is empty");
}
else
{
[Link]("The elements of stack are");
for(i=top;i>=0;i--)
{
[Link](stack[i]);
}
}
}
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
stack_operations obj=new stack_operations();
[Link]("Implementation of Stack operations");
ch=1;
while(ch==1)
{
Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 2
[Link]("Enter your choice");
[Link]("[Link]\[Link]\[Link]\[Link]");

choice=[Link]();
switch(choice)
{

case 1: [Link]();
break;
case 2: [Link]();
break;
case 3: [Link]();
break;
case 4: [Link]("Enter 1 to continue or 0 to exit");
ch=[Link]();
break;
}
}

}
}
Output:

Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 3
Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 4
Prepared by,
Ms. Sridevi S, AP/SoCSE, Ms. Meena Kumari, AP/SoCSE, Ms. Rohini A, AP/SoCSE 5

Common questions

Powered by AI

The implementation follows the LIFO principle by always adding (push) and removing (pop) elements from the top of the stack. This is crucial because LIFO ensures that the most recently added element is accessed first, which is essential for stack-based algorithms and applications such as recursive function execution, backtracking problems, and memory management scenarios .

The display method outputs "Stack is empty" when the top index is -1, indicating no elements have been pushed onto the stack or all have been popped. This condition assists in debugging by immediately showing the stack's state, highlighting situations where operations are attempted on an empty stack, thus preventing undefined behavior and enhancing visibility into stack management .

The choice-driven menu in the main method allows users to select operations by prompting them to enter a number corresponding to the desired action: 1 for push, 2 for pop, 3 for traversal, and 4 for exit. This is implemented using a while loop that continues as long as the choice is to keep performing operations (ch == 1). After each operation, the user is asked if they want to continue or exit, allowing for interactive and controlled stack management .

To enable dynamic resizing, the stack class could implement a method to double the array size when a push operation detects that the stack is full. This involves creating a new array with double the size of the original, copying existing elements to the new array, and updating the stack reference. This enhancement would allow the stack to handle more elements beyond its initial fixed size, thus adapting to varying data loads more flexibly .

The key functions implemented for stack operations using an array in Java include push, pop, and display. The push function adds an element to the top of the stack if there is space, otherwise it reports a stack overflow. The pop function removes the element at the top of the stack if the stack is non-empty, otherwise it reports a stack underflow. The display function shows all elements from top to bottom if the stack is not empty, otherwise it indicates that the stack is empty .

To handle generic types in Java, the stack class can be refactored using generics, allowing it to store elements of any object type. This involves defining the stack class with a type parameter, e.g., 'public class Stack<T>', and replacing specific data types such as int with the generic type T. This enables the stack to be type-safe, reusable for different data types, and reduces the need for casting elements when retrieved from the stack .

To support multi-threaded environments, the stack implementation can employ synchronization mechanisms. Using synchronized blocks or methods ensures that only one thread can modify the stack at a time, preventing data races. Additionally, implementing locking strategies like using Java's ReentrantLock class could provide more control over thread access, thus making stack operations thread-safe without causing performance bottlenecks .

Static variables in this implementation, such as the stack array, top index, and value, are shared across all instances of the class. This means they consume memory only once, enabling efficient memory utilization. However, using static variables also means the state of the stack is shared globally, which could lead to issues in a multi-threaded environment where the stack operations might interfere with each other if not properly synchronized .

The stack array implementation handles overflow by checking if the top index reaches the maximum size of the array (in this case, 4). If the maximum size is exceeded, the function reports 'Stack Overflow'. Similarly, for underflow, it checks if the top is -1 before attempting to pop an element, reporting 'Stack Underflow' if true. These conditions ensure program stability by preventing unauthorized access beyond the stack's allocated memory, which could otherwise cause runtime errors or crashes .

The Scanner class is used for user input, which facilitates data entry from the console. While functional, Scanner can pose reliability issues such as blocking the program if unexpected input types are received. Enhancements could include implementing exception handling with try-catch blocks to manage non-integer inputs more gracefully. Additionally, interactive GUI applications or robust command-line interfaces could provide more user-friendly alternatives and improve reliability .

You might also like