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

class Codeaft 
{
    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
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Blueberry Apple Cherry Grapes Mango Orange Apple codeaft@codeaft:~$
Java Stack: empty() and search() methods
Codeaft.java
import java.util.Stack;

class Codeaft 
{
    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
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft [Apple, Orange, Mango, Grapes, Cherry, Apple, Blueberry] false 6 1 -1 -1 codeaft@codeaft:~$
Java Stack: peek() and pop() methods
Codeaft.java
import java.util.Stack;

class Codeaft 
{
    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
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Peek element: Blueberry Popping: Blueberry Stack elements: Apple Cherry Grapes Mango Orange Apple codeaft@codeaft:~$
Comments and Reactions