Java Exercises: Count all the elements in a stack

Java Stack: Exercise-7 with Solution

Write a Java program to count all the elements in a given stack.

Sample Solution:

Java Code:

import java.util.Scanner;
public class Stack {
  private int[] arr;
  private int top;

  // Constructor to initialize the stack
  public Stack(int size) {
    arr = new int[size];
    top = -1;

  // Method to push an element onto the stack
  public void push(int num) {
    if (top == arr.length - 1) {
      System.out.println("Stack is full");
    } else {
      arr[top] = num;

  // Method to pop an element from the stack
  public int pop() {
    if (top == -1) {
      System.out.println("Stack Underflow");
      return -1;
    } else {
      int poppedElement = arr[top];
      return poppedElement;

  // Method to get the top element of the stack
  public int peek() {
    if (top == -1) {
      System.out.println("Stack is empty");
      return -1;
    } else {
      return arr[top];

  // Method to check if the stack is empty
  public boolean isEmpty() {
    return top == -1;

  // Method to count elements
  public int count() {
    return top + 1;

  public void display() {
    if (top == -1) {
      System.out.println("Stack is empty");
    } else {
      System.out.print("Stack elements: ");
      for (int i = top; i >= 0; i--) {
        System.out.print(arr[i] + " ");

  public static void main(String[] args) {
    System.out.println("Initialize a stack:");
    Stack stack = new Stack(10);
    System.out.println("\nInput some elements on the stack:");
    int ctr = stack.count();
    System.out.println("\nNumber of elements in the said stack: " + ctr);

Sample Output:

Input some elements on the stack:
Stack elements: -1 5 7 0 2 3 1

Number of elements in the said stack: 7


Flowchart: Java  Exercises: Count all the elements in a stack.
Flowchart: Java  Exercises: Count all the elements in a stack.
Flowchart: Java  Exercises: Count all the elements in a stack.

Live Demo:

Java Code Editor:

Improve this sample solution and post your code through Disqus

Java Stack Previous: Remove all the elements from a stack.
Java Stack Exercises Next: Check if an element is present or not in a stack.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Java: Difference between StringBuilder and StringBuffer

StringBuffer is synchronized, StringBuilder is not:

Ref: https://bit.ly/3rOJQuT