Write a Java program to get the size of Stack collection
The code demonstrates how to get the size of a stack in Java using the size() method. Let's break down the code:
- The code starts by importing the necessary libraries: java.io.* and java.util.*.
- The GetSize class is defined, serving as the entry point of the program.
- In the main method, a new stack object named stack_list is created using the raw Stack class. It is recommended to use generics to provide type safety.
- Several strings, namely "Pink," "Yellow," "Blue," "Green," and "Red," are pushed onto the stack using the push method.
- The System.out.println statement is used to print the size of the stack by concatenating the stack's size (obtained using the size() method) with the string "Size of Stack: " using the + operator.
Source Code
import java.io.*;
import java.util.*;
public class GetSize
{
public static void main(String[] args)
{
Stack stack_list = new Stack();
stack_list.push("Pink");
stack_list.push("Yellow");
stack_list.push("Blue");
stack_list.push("Green");
stack_list.push("Red");
System.out.println("Size of Stack: " + stack_list.size());
}
}
Output
Size of Stack: 5