Java Program to Create a Stack Collection of Objects of a Class

You are currently viewing Java Program to Create a Stack Collection of Objects of a Class

Java program to create a Stack collection of objects of a class

// Java program to create a Stack collection of 
// objects of a class

import java.util.*;

class Complex {
  int real, img;

  Complex(int r, int i) {
    real = r;
    img = i;
  }
}
public class Main {
  public static void main(String[] args) {
    int i = 0;
    Stack < Complex > stk = new Stack < Complex > ();

    stk.push(new Complex(10, 20));
    stk.push(new Complex(20, 30));
    stk.push(new Complex(30, 40));
    stk.push(new Complex(40, 50));

    System.out.println("Stack items: ");

    for (i = 0; i < 4; i++) {
      Complex C = stk.pop();
      System.out.println(C.real + " + " + C.img + "i");
    }
  }
}

Output

Stack items: 
10 + 20i
20 + 30i
30 + 40i
40 + 50i

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply