A Demo Class

Here is a class called Stack that implements a stack for integers:

  

class Stack {
  int stck[] = new int[10];
  int tos;
  Stack() {
    tos = -1;
  }
  void push(int item) {
    if (tos == 9)
      System.out.println("Stack is full.");
    else
      stck[++tos] = item;
  }
  int pop() {
    if (tos < 0) {
      System.out.println("Stack is empty.");
      return 0;
    } else
      return stck[tos--];
  }
}

public class Main {
  public static void main(String args[]) {
    Stack mystack1 = new Stack();
    for (int i = 0; i < 10; i++){
      mystack1.push(i);
    }
    for (int i = 0; i < 10; i++){
      System.out.println(mystack1.pop());
    }
  }
}  

This program generates the following output:


9
8
7
6
5
4
3
2
1
0
Home 
  Java Book 
    Class  

Class Creation:
  1. Introducing Classes
  2. A Simple Class
  3. A Closer Look at new
  4. Variables and Initialization
  5. this Keyword
  6. A Demo Class
  7. The Person class: another demo
  8. Understanding static