Develop a stack class to hold a maximum of 10 integers with suitable methods. Develop a JAVA main method to illustrate Stack operations
PROGRAM:
package
jo;
import
java.util.*;
public
class Stack {
int
top; // define top of
stack
int
maxsize = 10; //
max size of the stack
int[]
stack_arry = new
int[maxsize];
// define array that will hold stack elements
Stack() {
top
= -1;
}
boolean
isEmpty() {
return
(top < 0);
}
boolean
push(int val)
{
if
(top == maxsize
- 1) {
System.out.println("Stack
Overflow !!");
return
false;
} else
{
top++;
stack_arry[top]
= val;
return
true;
}
}
boolean
pop() {
if
(top == -1) {
System.out.println("Stack
Underflow !!");
return
false;
} else
{
System.out.println("Item
popped: " + stack_arry[top--]);
return
true;
}
}
void
display() {
System.out.println("Printing
stack elements..... ");
for
(int i
= top; i
>= 0; i--) {
System.out.println(stack_arry[i]);
}
}
// ✅ main method
public
static void
main(String[] args)
{
Stack stck
= new Stack();
stck.push(10);
stck.push(20);
stck.push(30);
stck.push(40);
System.out.println("\nAfter
Push Operation...");
stck.display();
stck.pop();
stck.pop();
System.out.println("\nAfter
Pop Operation...");
stck.display();
}
}
}
viva questions
1) What
is Constructor?
A constructor in Java is a special method that is automatically called
when an object is created.
- Its name is the same as the
class name.
- It has no return type
(not even void).
- It is used to initialize
object variables.
Example:
class Demo {
int x;
Demo() {
// constructor
x =
10;
}
}
2) What
is Stack?
A stack is a linear data structure that follows the LIFO
principle — Last In, First Out.
- The last element inserted is
the first one removed.
- Think of it like a stack of plates
— you put on top, and take from the top.
3) What
are all the operations performed on a stack?
Common stack operations are:
- push(x) → Add an element on top of
the stack.
- pop() → Remove the top element
from the stack.
- peek() / top() → View the top element
without removing it.
- isEmpty() → Check if the stack is
empty.
- (Sometimes) isFull() → Check if
the stack is full (for fixed-size stacks).
4) What
is the role of top in a stack?
- top is an index (pointer)
that keeps track of the position of the last inserted element in
the stack.
- Initially, top = -1 (stack is empty).
- When we push, top is incremented.
- When we pop, top is decremented.
- It helps in knowing where
the next element should be inserted or removed.
No comments:
Post a Comment