when to use Stack st = new Stack();
?
Never. That style predates the existence of generics in Java. It’s completely replaced by generic usage, i.e. Stack<Integer>
. Sometimes you need to use late binding and don’t know which type will be stored inside the stack. But even then you’re supposed to use wildcards, i.e. something like Stack<?>
.
A modern IDE will warn you if you use a generic class without specifying generic parameters.
I will have to create my own class Stack
You don’t, you could use the generic Stack
class (that is, java.util.Stack<T>
) non-generically. Java allows that (for any generic class, not just for Stack
). But it’s discouraged, see above.