Java Programing laungage

java.util Projects

java.util Project 1

Stack Implementation

In this programming tutorials we shall be learn how to implement a stack in Java. A Stack is like a bucket in which we can put elements one-by-one in sequence and retrieve elements from the bucket according to the sequence of the last entered element.

Previous Home Next
adplus-dvertising

Stack is a collection of data and follows the LIFO (Last in, first out) rule that mean you can insert the elements one-by-one in sequence and the last inserted element can be retrieved at once from the bucket. Elements are inserted and retrieved to/from the stack through the push() and pop() method.

Stack(): This constructor of the Stack class is used to creates an empty stack in which we can push the value which is mention with the creation of stack.

Stack.push(Object obj): This method is used to insert or push the data or element in the stack.

Stack.pop(): This is the method to removes the objects like data or elements at the top positions of stack.

example


package r4r;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class stacktests {
Stack<Integer> stack;
String str;
int num, n;
public static void main(String[] args){
stacktests s = new stacktests();
}
public stacktests(){ try{ stack = new Stack<Integer>(); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.print("Enter the elements No. : "); str = br.readLine(); num = Integer.parseInt(str); for(int i = 1; i <= num; i++){ System.out.print("Enter elements : "); str = br.readLine(); n = Integer.parseInt(str); stack.push(n); } } catch(IOException e){} System.out.print("Fetch elements from the stack : "); while (!stack.empty()){ System.out.print(stack.pop() + " "); } } }
Previous Home Next