Program to demonstrate "Stack" class in Java's Collection Framework

The Stack class implements a LIFO (Last In First Out) stack of elements. For example, stack of coins. When you add a new element, it gets stacked on top of the others. When you pull an element off the stack, it removes the element at top. Hence it is called as LIFO (Last In First Out) or FILO (First In Last Out).

Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector and adds several of its own. Stack class has following methods:
  1. boolean empty( ) : Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.
  2. Object peek( ) : Returns the element on the top of the stack, but does not remove it.
  3. Object pop( ) : Returns the element on the top of the stack, removing it in the process.
  4. Object push(Object element) : Pushes element onto the stack. element is also returned.
  5. int search(Object element) : Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, .1 is returned.

PROGRAM
import java.util.Stack;

class StackDemo {

 public static void main(String[] args) {

  Stack<String> p=new Stack<String>();
  p.push("Apple");
  p.push("Mango");
  p.push("Pine");
  p.push("Orange");
  
  while(!p.empty()) {
   
   System.out.println(p.pop());
  }
 }
}
OUTPUT
C:\>javac StackDemo.java
C:\>java StackDemo
Orange
Pine
Mango
Apple

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative