Saturday, November 24, 2012

Apply STACK class in code !!! (java.util.Stack)


Why we use STACK class?

Normally STACK class is not in use that much except in some programme where there is necessary to apply that. In STACK class it use LIFO method that is Last in First Out. For example if you push 1 2 3 4, it will pop like 4 3 2 1. You can see same thing happen in our below code. In STACK we use keyword like 'push' and 'pop', most of you guys know this because same thing we use in couple of algorithms. 'pop' mean removed and 'push' mean inserted, that's very easy. To call this class we write 'import java.util.Stack' in starting of the code.

__________________________________________________


import java.util.Stack;

public class Stack1 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Stack number = new Stack();

for(int x = 10;x>=1;x--){

number.push(new Integer(x));
}

while (!number.empty()){
System.out.print(number.pop());
System.out.print('-');
}
System.out.println("That's enough now !");
}

}
____________________________________________________

Output:

1-2-3-4-5-6-7-8-9-10-That's enough now !
_________________________________________________


In above programme, we start from 10 and till 1 so when it will pop than it is start from correct sequence that is 1 2 3 4 and so on..........

Hope you guys like this.................

If you find this post useful than please share it to your friends..............

No comments:

Post a Comment