Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Stack in java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 110
    Comment on it

    In stack, we save elements in last-in, first-out manner. Stack extends the Vector class and have only one constructor that is default. By this default constructor, we can create an empty stack.


    Below is the example.

    public class ExampleStack { 

    static void showpush(Stack stack, int value) { stack.push(new Integer(value)); System.out.println("push<" + value + ">"); System.out.println("stack: " + stack); }

    static void showpop(Stack stack) { System.out.print("pop/delete -> "); int value = (Integer) stack.pop(); System.out.println(value); System.out.println("stack>>> " + stack); }

    public static void main(String args[]) { Stack stack = new Stack(); showpush(stack, 13); showpush(stack, 52); showpush(stack, 62); showpop(stack); showpop(stack); showpop(stack); try { showpop(stack); } catch (EmptyStackException e) { System.out.println("Stack is empty !!!"); } } }

    Output:

    stack>>> [ ] 
    push(13) 
    stack>>> [42] 
    push(52) 
    stack>>> <13, 52> 
    push(62) 
    stack>>> <13, 52, 62> 
    pop/delete ->62 
    stack>>> <13, 52> 
    pop -> 52 
    stack>>> <13> 
    pop -> 13 
    stack>>>  [ ] 
    pop/delete -> Stack is empty !!! 

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: