Q:

stack class in java

// construct with non-primative elements only!
Stack<String> stack = new Stack<String>();

// to add a value to the top of the stack:
stack.push("Hello");

// to return and remove a value from the top:
String top = stack.pop();

// to return a value without removing it:
String peek = stack.peek();
15
import java.util.Stack<E>;
Stack<Integer> myStack = new Stack<Integer>();
myStack.push(1);
myStack.pop();
myStack.peek();
myStack.empty(); // True if stack is empty
9
import java.util.Stack;
class Main {
    public static void main(String[] args) {
        Stack<String> animals= new Stack<>();
        // Add elements to Stack
        animals.push("Dog");
        animals.push("Horse");
        // Remove element from Stack
      	animals.pop();
      	// Access element from top of Stack
      	animals.peek();
    }
}
4
// Java code to illustrate push() method 
import java.util.*; 
  
public class StackDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Stack 
        Stack<Integer> STACK = new Stack<Integer>(); 
  
        // Use push() to add elements into the Stack 
        STACK.push(10); 
        STACK.push(15); 
        STACK.push(30); 
        STACK.push(20); 
        STACK.push(5); 
  
        // Displaying the Stack 
        System.out.println("Initial Stack: " + STACK); 
  
        // Pushing elements into the Stack 
        STACK.push(1254); 
        STACK.push(4521); 
  
        // Displaying the final Stack 
        System.out.println("Final Stack: " + STACK); 
    } 
} 
2

New to Communities?

Join the community