Stack example in Java - push(), pop(), empty(), search()

By: Henry Emailed: 1605 times Printed: 2074 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.

To put an object on the top of the stack, call push(). To remove and return the top element, call pop(). An EmptyStackException is thrown if you call pop( ) when the invoking stack is empty. You can use peek( ) to return, but not remove, the top object.

The empty() method returns true if nothing is on the stack. The search() method determines whether an object exists on the stack, and returns the number of pops that are required to bring it to the top of the stack. Here is an example that creates a stack, pushes several Integer objects onto it, and then pops them off again:

// Demonstrate the Stack class.
import java.util.*;
class StackDemo {
static void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}

The following is the output produced by the program; notice how the exception handler for EmptyStackException is caught so that you can gracefully handle a stack underflow:

stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(29)


1. View Comment

Hi,

Thanks for this example (glad to have found this site! Bookmarked it too) however - if possible - please enhance it with a search() - what I was after tonight...(sat 6 sept 23:16 - yep I know...)


View Tutorial          By: Thor at 2007-10-06 15:12:28
2. View Comment

if i wanna push the data from my keyboard input, how the syntax is?

View Tutorial          By: andys at 2008-11-09 03:09:32
3. View Comment

help me for learning to programing with java
iam from iraq


View Tutorial          By: hemn at 2008-11-25 03:12:19
4. View Comment

Hi! Thanks for the examples posted here...it really helps me a lot! Hope we can learn more from you guys! More power..

View Tutorial          By: creece at 2009-01-23 17:28:33
5. View Comment

pls give us aprogram of postfix and infix using stack java....pls. send in this email tnx so much....lost_hope1111@yahoo.com

View Tutorial          By: lost_hope1111 at 2009-02-13 01:48:37
6. View Comment

thanks for this example but i want the whether there is a complexity of the stack is in array or the java.util package. please sent me on my email id.

View Tutorial          By: Rupesh Chavan at 2010-03-14 07:36:31
7. View Comment

lots of thanks for this given example........hope u could create more example in java programming..... ty

View Tutorial          By: virgi crisostomo at 2010-08-18 17:18:08
8. View Comment

please help me to do find a push and pop operation with stack operation using the case statement

View Tutorial          By: sweet mae at 2011-01-14 00:01:33
9. View Comment

for user input use this method....
1. import java.io.*;
2.for input:
InputStreamReader ob1 =new InputStreamReader(System.in);
BufferedReader ob2=new BufferedReader(ob1);
System.out.println("Enter no:");
int i=Integer.parseInt(ob2.readLine());
System.out.println("input string:"+i);


View Tutorial          By: susmit at 2011-03-02 09:09:46
10. View Comment

import java.io.*;
import java.util.Stack;
public class Stacks {
public static void main(String args[])throws IOException {
DataInputStream k=new DataInputStream(System.in);
Stack r=new Stack();
for(int i=1; i<=3; i++) {
System.out.print(" ");
System.out.print("Enter a value to PUSH: ");
int x=Integer.parseInt(k.readLine());
r.push (new Integer(x) );
System.out.print("Stacked: "+r+"\n");

}System.out.println("STACK IS FULL!");
do {
for(int i=1; i<=3; i++) {
System.out.print(" "
);
System.out.print("Enter a value to POP: ");
int x=Integer.parseInt(k.readLine());
r.pop();
System.out.print("Stacked: "+r+"\n");
}
}while(!r.empty());
System.out.println("STACK IS EMPTY!");
}
}


View Tutorial          By: jack&jill at 2011-07-26 06:40:32
11. View Comment

pls give me example of stack class with postfix method and pop and push...tnx

View Tutorial          By: uchiha at 2011-09-16 04:02:57
12. View Comment

pls send to me example about stacks
because i cant understand it


View Tutorial          By: suliman at 2011-12-10 08:02:01
13. View Comment

Thanks

View Tutorial          By: PARIKSHIT SHARMA at 2011-12-23 22:33:39
14. View Comment

THANKS you for having this site. it help me a lot on my report..
but I am more please if its have a chart on how the process is going on.. thank you â¥â¥â¥


View Tutorial          By: fermilita at 2012-01-04 11:45:53
15. View Comment

Thank you lot of..@
This example help me.


View Tutorial          By: Tushar at 2012-02-12 02:48:10
16. View Comment

Thnx A Lot...very healpful...........

View Tutorial          By: vinay at 2012-07-19 09:21:20
17. View Comment

Thanks a lot man !
PEace


View Tutorial          By: Karan Vohra at 2012-08-30 02:15:05
18. View Comment

please give some examples of postfix and infix.

View Tutorial          By: john mark at 2012-10-07 13:55:04
19. View Comment

please help me on "why subclass of stack is freeze in collection of java frame work? "

View Tutorial          By: mahendra at 2012-12-15 03:39:22
20. View Comment

Thanks for the example taken directly from the Java Software Structures book by Dr. Chase and Dr. Lewis

View Tutorial          By: Lewis Chase at 2013-09-24 23:39:21
21. View Comment

Please tell me how to display the contents of stack for this program

View Tutorial          By: Senthil at 2014-05-21 21:44:05
22. View Comment

import java.io.*;
import java.util.*;
class Stackdemo
{
public static void main(String []args)throws IOException
{
Stack<Integer> st=new Stack<>();
Buffer Reader br =new Buffer Reader(new InputStreamReader(System.in));
int element,pos,choice=0;
while(choice<4)
{
System.out.println("stack operation");
System.out.println("1 push element");
System.out.println("2 pop element");
System.out.println("3 search for element");
System.out.println("4 exit");
System.out.println("your choice");
choice=Integer.parseInt(br.readline());
switch(choice)
{
case1:
System.out.print("enter element:");
element =Integer.parseInt(br.readline());
st.push(element);
break;
case2:
Integer i=st.pop();
System.out.print("poped="+i);
break;
case3:
System.out.print("enter element");
element=Integer.parseInt(br.readline());
pos=st.search(element);
if(pos==-1)
System.out.println("element not found");
else
System.out.println("element found position:"+pos);
break;
default;
return;
}
System.out.println("Stack="+st);
}
}
}




}


View Tutorial          By: srikanth at 2014-05-30 06:44:58
23. View Comment

public class zcxzcStack
{
//push function/method
// please change the code thank you
static int[] push(int [] stack, int element, int top )
{
stack[++top] = element;
return stack;
}
// please change the code thank you
//pop function/method
static int[] pop(int [] stack, int top)
{
int pop = 0;
stack[top--] = pop;
return stack;
}
// please change the code thank you
//display
public static void main (String[]args)
{
int stack[] = new int[10];
int top = -1;

//push
stack = push(stack,12,top++);
stack = push(stack,13,top++);
stack = push(stack,14,top++);

/*//Pop
stack = pop(stack,top--);

*/
//set elements to -1;
// please change the code thank you
for ( int i = 0; i < stack.length; i++ )
if (stack[i] !=0 )
System.out.print(stack[i] + " ");
System.out.println();
// please change the code thank you
}
}


View Tutorial          By: eissen at 2014-09-22 13:32:20
24. View Comment

How can I use stack in entering a letter and will reverse immediately?

View Tutorial          By: mards at 2014-10-17 12:18:34
25. View Comment

pls help on me to program in c++, write a program in c++ (1)enter 10 integer (2) pushing on stack/ popping user choice (3)pushing on Queue/popping from user choice (4)bring the integer in order/sorting user choice(+,-,*,/), PLEASE HELP ME ON THIS PROGRAM. THANKS

View Tutorial          By: Hamid at 2014-12-18 20:41:40
26. View Comment

why push is error in st.push(new Integer(a)); ? and pop in Integer a = (Integer) st.pop();??

View Tutorial          By: ann at 2015-02-02 09:23:41
27. View Comment

that is fifo rigth? how about lifo?

View Tutorial          By: galz at 2015-02-18 03:03:31
28. View Comment

can i using stack in microsoft access 2007

View Tutorial          By: pxin at 2015-03-24 05:45:56
29. View Comment

how to implement stack with using vector class

View Tutorial          By: anamika at 2015-08-25 18:58:29

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Henry
Generating Your Key Pair example using keytool in Java
Summary of Operators in Java
JDBC Basics and JDBC Components
The IterationTag Interface in JSP
Trigonometric, Hyperbolic, Exponential and Logarithmic Functions in C
Using Bit-field in C
Java Beans and the Expression Language
Initialization of Variables in C
Creating Struts Modules
else if statement in C
Line Counting sample program in C
Accessing Context Data in Beans using JSF
Using peek() and putback() with cin in C++
Internationalization Support in J2ME MIDP
java.lang.SecurityException: MIDP lifecycle does not support system exit.

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
XML and Java - Parsing XML using Java Tutorial
Integer: byte, short, int, and long data types in Java
Student marks calculation program in Java
clone() and the Cloneable Interface in Java
How to Send SMS using Java Program (full code sample included)
Count number of vowels, consonants and digits in a String in Java
Stack example in Java - push(), pop(), empty(), search()
append() in Java
Introducing Access Control
Supports mobile tournament games
The Main Thread in Java
The Basic Structure of a Simple Java program
The switch Statement example in Java
indexOf( ) and lastIndexOf( ) in Java
The Benefits of OOP
Most Emailed Articles (in Java)
What is Java?
How to Send SMS using Java Program (full code sample included)
inheritance in Java
instanceof sample program in Java
Use of return statement in Java
Using PrintWriter in Java
Method Overriding in Java
Using StringTokenizer in Java
Recursion in java
The java Buzzwords
Student marks calculation program in Java
Handling Fractions in Java
Multiple Inheritance sample in Java
Java program to display numbers from 1 to 10 on Applet
How to create wav file using freetts