In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.

int[] i = new int[10];

The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:

int[] i = new int[11];

In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.

Answer from Kennet on Stack Overflow
Top answer
1 of 5
56

In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.

int[] i = new int[10];

The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:

int[] i = new int[11];

In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.

2 of 5
25

For those who don't have time to refactor the code to replace arrays with Collections (for example ArrayList), there is an alternative. Unlike Collections, the length of an array cannot be changed, but the array can be replaced, like this:

array = push(array, item);

The drawbacks are that

  • the whole array has to be copied each time you push, and
  • the original array Object is not changed, so you have to update the variable(s) as appropriate.

Here is the push method for String:
(You can create multiple push methods, one for String, one for int, etc)

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    for (int i = 0; i < array.length; i++)
        longer[i] = array[i];
    longer[array.length] = push;
    return longer;
}

This alternative is more efficient, shorter & harder to read:

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    System.arraycopy(array, 0, longer, 0, array.length);
    longer[array.length] = push;
    return longer;
}
๐ŸŒ
AlgoCademy
algocademy.com โ€บ link
Array Pop in Java | AlgoCademy
Learn "Array Pop in Java" with our free interactive tutorial. Master this essential concept with step-by-step examples and practice exercises.
Discussions

java howto ArrayList push, pop, shift, and unshift - Stack Overflow
Also note that corner-case behaviors ... between Java and JS, since they each have their own standards. ... Sign up to request clarification or add additional context in comments. ... If you're doing a lot of "unshifting" but not a lot of getting at middle indices, you may find ArrayList to be inferior ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Why is ArrayList not a Stack - Software Engineering Stack Exchange
Moreover, peek and pop operations on an ArrayList are exactly not very likely to be a lot less efficient than for a on-purpose Stack. ... Like I said in the OP, there are cases where the overlap between list and stack is preferred for clean code. The examples I gave both need to peek 'deeper' into the stack without popping everything. Furthermore, any Stack (except PriorityStacks) has a fixed order: the iteration order. ... @DocBrown The question is "Why doesn't Java ... More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
September 27, 2024
java - Stack using an array - Code Review Stack Exchange
If the marker for the top reaches 0, it is set to size of array-1 so elements can still be popped in correct order. The output I'm getting looks fine to me. No null references or objects in the wrong place, etc. I've tested it pushing in Character and Integer objects. package CAStack; import java.... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
September 2, 2015
algorithm - Stack Array implementation of Java - Code Review Stack Exchange
This is my array implementation on stack in Java. It involves push, pop, get and growth when limit of array size is reached. I am a self-taught programmer starting to learn data structures and More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
November 19, 2018
๐ŸŒ
Java array pop
regealpine.mystrikingly.com โ€บ blog โ€บ java-array-pop
Java array pop
November 1, 2023 - Return Value: This method returns the element present at the top of the stack and then. Syntax: STACK.pop () Parameters: The method does not take any parameters. The element is pop
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ java โ€บ util โ€บ arraydeque_pop.htm
Java ArrayDeque pop() Method
The following example shows the usage of Java ArrayDeque pop() method with Integers. We're creating an ArrayDeque of Integers, adding some elements, print it and then use pop() method to get the first element.
๐ŸŒ
HowToDoInJava
howtodoinjava.com โ€บ home โ€บ data structure โ€บ stack using array
Java Stack Implementation using Array
March 31, 2023 - This tutorial gives an example of implementing a Stack data structure using an Array. The stack offers to put new objects on the stack (push) and to get objects from the stack (pop). A stack returns the object according to last-in-first-out (LIFO). Please note that JDK provides a default java stack ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ arraydeque-pop-method-in-java
ArrayDeque pop() Method in Java - GeeksforGeeks
December 10, 2018 - Your All-in-One Learning Portal. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
Find elsewhere
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-the-arraydequepop-method-in-java
What is the ArrayDeque.pop method in Java?
This class is the implementation class of the Deque interface. ArrayDeque can be used as a stack or queue. Null elements are prohibited. The pop method can be used to get and remove the first element of the ArrayDeque object.
๐ŸŒ
EDUCBA
educba.com โ€บ home โ€บ software development โ€บ software development tutorials โ€บ java tutorial โ€บ java pop
Java Pop | How does the pop method work in Java with Examples?
March 30, 2023 - Guide to Java Pop. Here we discuss How does the pop method work in Java and Examples along with the codes and outputs in detail.
Call ย  +917738666252
Address ย  Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
๐ŸŒ
AlgoCademy
algocademy.com โ€บ link
Array Push in Java | AlgoCademy
Learn "Array Push in Java" with an interactive walkthrough. Try the first step for free โ€” no signup required.
๐ŸŒ
LinkedIn
linkedin.com โ€บ all โ€บ engineering โ€บ programming
How can you implement a stack using an array in Java?
January 18, 2024 - Learn how to create a stack data structure using an array in Java. Discover the basic operations of push, pop, peek, isEmpty, and isFull. See a code example of the stack class.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 8 โ€บ docs โ€บ api โ€บ java โ€บ util โ€บ ArrayDeque.html
ArrayDeque (Java Platform SE 8 )
April 21, 2026 - Javaโ„ข Platform Standard Ed. 8 ... public class ArrayDeque<E> extends AbstractCollection<E> implements Deque<E>, Cloneable, Serializable
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Array โ€บ pop
Array.prototype.pop() - JavaScript - MDN Web Docs
The pop() method of Array instances removes the last element from an array and returns that element. This method changes the length of the array.
Top answer
1 of 4
5

We can only guess why the JCF looks today like it does, but one lesson learned in design is what Antoine de Saint-Exupery once said:

A designer knows he has achieved perfection not when there is nothing left to add, but when there is nothing left to take away.

In my experience, this applies to software design as well. A component like an ArrayList does not become necessarily "better" by supporting as many different data type interfaces as possible (even if it could). The smaller the interface of a component is, the less do we we have to learn and remember how it looks like, and the less functions are there which we confuse for each other. (Of course, an interface should not be smaller than it needs to be to form a coherent abstraction.)

How "small" an interface of a container should be ideally is definitely a question of the designers experience, taste and what they have learned at school or university. The usual CS books about stacks, lists, vectors, queues and arrays treat them as distinct abstract data types, so following that tradition and implementing them as different classes seemed to be quite natural.

Hence, for some reason we do not know for sure, the JCF designers seemed to have thought peek and pop are negligible for ArrayList. But when you think peek and pop would be a great addition to your ArrayLists, feel free to implement your own component ExtArrayList which provides the whole ArrayList together with peek and pop.

2 of 4
5

Have you seen this?

Stack Overflow - Rule of thumb for choosing an implementation of a Java Collection?

So tell me, how did you land on ArrayList if you wanted to treat it like a LIFO or a queue?

I know ArrayList is popular. If you got stuck with it somehow and don't really have a choice of implementation don't feel bad about wrapping it up in something that lets its client treat it like a stack. It might not be the most performant choice but good enough is good enough.

But don't act like every possible interface that could have been backed by ArrayList should be native to ArrayList. That list of interfaces has no end. They focused on what they made it for and hoped the kitchen sink could be added later.

Also how would anyone know which end list.pop() would pop from? What makes stack so special? Sorry but if I can see the ArrayList behind the stack then your abstraction is leaking.

Top answer
1 of 1
3

Terminology

This is going to be confusing. What you call size() is conventionally called the "capacity". You got the terminology mostly right in the parameter to the constructor. There's no point in calling it initialCapacity instead of just capacity, though, since the data structure's capacity cannot be changed once it is created.

You don't offer a way for users to fetch the size (i.e. the number of pushes minus the number of pops). That's what the size() method should be for. In addition, there should be a way to find out how many elements are available to be popped (that haven't been discarded).

I don't know what you mean by bottomElem โ€” it is never used.

Style

Your block comments would be much more valuable if you wrote them as standard JavaDoc, like in the interface file.

The DEFAULT_CAPACITY is only discoverable by reading the source code or by decompiling the bytecode. Furthermore, I don't see any obvious reason for picking 100. You should either explain what the default constructor does in JavaDoc or drop the default constructor altogether.

Omitting braces is a filthy habit. You will contribute to a future coding accident, and it will be squarely your fault.

Code should compile without warnings. You should write @SuppressWarnings("unchecked") to suppress this warning:

CircularArrayStack.java:50: warning: [unchecked] unchecked cast
          stack = (T[])(new Object[initialCapacity]);
                       ^
  required: T[]
  found:    Object[]
  where T is a type-variable:
    T extends Object declared in class CircularArrayStack
1 warning

Behaviour

This is a weird data structure. I can't imagine any practical application for it. Note the following undesirable properties:

  • Once you push() one element, you can call pop() as many times as you want, and it will never be empty.
  • If you push() more elements than the capacity, it will silently overwrite earlier entries.
  • If you push() more elements than the capacity, toString() won't show all of the stored entries.
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2014 โ€บ 08 โ€บ linkedlist-push-and-pop-methods-java
LinkedList push() and pop() methods โ€“ Java
September 11, 2022 - Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java ยท Programs to demonstrate push and pop operations on LinkedList
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ remove-element-from-an-array-in-java
Remove Element from an Array in Java
December 16, 2021 - Due to the nature of array's memory placement, it is simply impossible to remove the element directly. Instead, to "remove" any element, all subsequent elements need to be shifted backward by one place. This will create an illusion that a specific element was removed. The simplest pure Java way ...