Switch to full style
Java Collections classes examples .
Post a reply

Stack using java

Wed Oct 24, 2012 10:45 pm

Java Stack Example (Push/PoP/Peak)

Code:


import java
.awt.Color;

public class 
StackExample {

    public static 
void main(String[] args) {

        
Color c1 = new Color(544375);
        
Color c2 = new Color(4100175);
        
Color c3 = new Color(10053160);
        
JavaStack stack = new JavaStack(2);

        
stack.push(c1);
        
stack.push(c2);
        
stack.push(c3);

        
System.out.println(stack.pop());
        
System.out.println(stack.pop());
        
System.out.println(stack.pop());// Empty
        
stack.push(c3);
        
stack.push(c2);
        
System.out.println(stack.pop());
        
System.out.println(stack.pop());
        
System.out.println(stack.pop());// Empty
        
System.out.println(stack.pop());// Empty


    
}
}
 


Code:
public class JavaStack {

    private 
int top;
    
// Array to store objects
    
private Object[] stackBox;

    
JavaStack(int capacity) {

        
stackBox = new Object[capacity];
        
top = -1;

    }

    
void push(Object value) {

        if (
top+== stackBox.length) {
            
System.out.println("For Value: " value ","
                    
" We can't add more values to the "
                    
" (Stack is full)");
        } else {
            
top++;
            
stackBox[top] = value;
        }

    }

    
Object peek() {

        if (
top == -1) {
            
System.out.println("Stack is empty");
            return 
null;
        } else {
            return 
stackBox[top];
        }

    }

    
Object pop() {

        if (
top == -1) {
            
System.out.println("Stack is empty");
            return 
null;
        } else {
           
// Decreases the value after assigning it stackBox
            
return stackBox[top--];
        }
    }

    
boolean isEmpty() {
         
// True if empty 
        
return (top == -1);

    }


}

 


The output is :
Code:
For Value: java.awt.Color[r=100,g=53,b=160], We can't add more values to the  (Stack is full)
java.awt.Color[r=4,g=100,b=175]
java.awt.Color[r=54,g=43,b=75]
Stack is empty
null
java.awt.Color[r=4,g=100,b=175]
java.awt.Color[r=100,g=53,b=160]
Stack is empty
null
Stack is empty
null




Post a reply
  Related Posts  to : Stack using java
 Code of stack     -  
 2d game in java-Monster-Java 2D Game Graphics and Animation     -  
 What is Java API?!!!     -  
 java or .net     -  
 need help in java     -  
 Using FTP in java     -  
 what is java     -  
 Java course     -  
 java statements     -  
 how to start java .     -  

Topic Tags

Java Collections