The stack data structure is a linear data structure that follows the Last In First Out (LIFO) principle.
This data stack can be imagined as a stack of cards in which the next element is put on top of the previous element.
When pulling elements from the stack, you can only pull the last element inserted.
Here’s a diagram explaining the stack data structure implementation in Java:
Java already has the Stack
class that you can use to create an instance of Stack
type.
To create a stack of char
type in Java, you can use the following syntax:
Stack<Character> myStack = new Stack<>();
You can’t use a primitive type when defining a Java generic type. You need to use the wrapper of the primitive type char
which is Character
.
This is why the variable myStack
above is defined as the Stack
object of Character
type.
Once you initialize the object, you can add as many char
type value as you need:
myStack.add('a');
myStack.add('b');
myStack.add('c');
System.out.println(myStack.peek()); // c
And that’s how you create a Stack
of char
type in Java. 😉