Java Stack: push() and empty() methods
KW.java
import java.util.Stack;

class KW 
{
    public static void main(String[] args) 
    {
        Stack<String> s=new Stack<>();
        s.push("Apple");
        s.push("Orange");
        s.push("Mango");
        s.push("Grapes");
        s.push("Cherry");
        s.push("Apple");
        s.push("Blueberry");
        
        while(s.empty()==false)
        {
            System.out.println(s.pop());
        }
        
        /*
         * for(String e:s) { System.out.println(e); }
         */
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW Blueberry Apple Cherry Grapes Mango Orange Apple kodingwindow@kw:~$
Java Stack: empty() and search() methods
KW.java
import java.util.Stack;

class KW 
{
    public static void main(String[] args) 
    {
        Stack<String> s=new Stack<>();
        s.push("Apple");
        s.push("Orange");
        s.push("Mango");
        s.push("Grapes");
        s.push("Cherry");
        s.push("Apple");
        s.push("Blueberry");
        System.out.println(s);
        
        System.out.println(s.empty());
        System.out.println(s.search("Orange"));
        System.out.println(s.search("Blueberry"));
        System.out.println(s.search("Pineapple"));
        System.out.println(s.search("Dates"));
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW [Apple, Orange, Mango, Grapes, Cherry, Apple, Blueberry] false 6 1 -1 -1 kodingwindow@kw:~$
Java Stack: peek() and pop() methods
KW.java
import java.util.Stack;

class KW 
{
    public static void main(String[] args) 
    {
        Stack<String> s=new Stack<>();
        s.push("Apple"); //First In Last Out
        s.push("Orange");
        s.push("Mango");
        s.push("Grapes");
        s.push("Cherry");
        s.push("Apple");
        s.push("Blueberry"); //Last In First Out
        System.out.println("Peek element: "+s.peek());
        
        System.out.println("Popping: "+s.pop());
        
        System.out.println("\nStack elements: ");
        while(s.empty()==false)
        {
            System.out.println(s.pop());
        }
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW Peek element: Blueberry Popping: Blueberry Stack elements: Apple Cherry Grapes Mango Orange Apple kodingwindow@kw:~$
Advertisement