1-
package STACK_DEMO;
public class STACK_ARRAY {
private int size;
private int top;
private int[] data;
public static final int default_capacity=10;
public STACK_ARRAY() throws Exception {
this(default_capacity);
}
public STACK_ARRAY(int capacity) throws Exception {
if(capacity<1) {
throw new Exception("INVALID CAPACITY");
}
this.data=new int[capacity];
this.top=-1;
}
public int size() {
return this.top+1;
}
public boolean isEmpty() {
return this.size()==0;
}
public void push(int value) throws Exception{
if(this.size()==this.data.length) {
throw new Exception("STACK IS FULL");
}
this.top++;
this.data[this.top]=value;
}
public int pop() throws Exception{
if(top==-1) {
throw new Exception("STACK IS EMPTY");
}
int rv=this.data[this.top];
this.data[this.top]=0;
this.top--;
return(rv);
}
public int top() throws Exception{
if(size==0) {
throw new Exception("STACK IS EMPTY");
}
int rv=this.data[this.top];
return(rv);
}
public void display() {
for(int i=this.top;i>=0;i--) {
System.out.print(this.data[i]+",");
}
System.out.println("END");
}
}
2-
package STACK_DEMO;
public class STACK_ARRAYCLIENT {
public static void main(String[] args) throws Exception{
STACK_ARRAY stack=new STACK_ARRAY(5);
for(int i=1;i<=5;i++) {
stack.push(i*20);
}
stack.display();
System.out.println(stack.size());
System.out.println(stack.top());
}
}