Java


Java Tutorial


Admission Enquiry Form

  

Stack in Java



Java Stack Example

//Stack in Java
import java.util.Iterator;
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack<String> st1=new Stack<>();
st1.push("html");
st1.push("css");
st1.push("js");
System.out.println("My stack :" + st1);
st1.pop();//will remove top value
System.out.println("Now My Stack is : " + st1);
System.out.println(st1.search("css"));//will return 1
System.out.println(st1.search("python"));//will return -1
System.out.println("Peek is " + st1.peek());//will display top element
st1.add("javascript");
System.out.println("Now Values of Stack are :");
//Displaying values through for each loop
for(String s :st1)
{
System.out.println(s);
}
//now using Iterator to display the elements of Stack
Iterator<String> it= st1.iterator();
System.out.println("Now the values of stack through Iterator ");
while(it.hasNext())
{
System.out.println(it.next());
}
}//end of main
}//end of class