Stack newStack = new Stack();
newStack.push(0);
OR
Stack.push(0);
Note: Here Stack is a user defined class to implement concept of stack manually in java and not the predefined one.
Stack newStack = new Stack();
newStack.push(0);
OR
Stack.push(0);
Note: Here Stack is a user defined class to implement concept of stack manually in java and not the predefined one.
This allows having multiple stacks for different purposes.
Stack newStack = new Stack();
newStack.push(0);
We can have only one stack when using this.
Stack.push(0);
I prefer the first one as it allows initializing multiple stacks at the same time which the second way can't do.
In the first example, push is a non-static method of the Stack class. In order to use the push method, you have to create an instance of the Stack class.
Stack newStack = new Stack();
newStack.push(0);
The equivalent code with an anonymous instance would be:
new Stack().push(0);
which would be kind of useless in this case, since you're eventually going to want to pop the stack you created.
In the second example, push is a static method of the Stack class.
Stack.push(0);
Nandu Raj is correct in his answer in that you can only have one Stack in your application, rather than more than one with the non-static push method.
Creating and using non-static methods is generally a better programming practice, although there are cases, like the Java Math class, where static methods work better.