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
An ArrayList in Java is a resizable array, which means it can grow and shrink in size dynamically. The .remove() method is used to delete an element at a specified index, shifting subsequent elements to the left.
Discussions

[JAVA] How Do I Use push() and pop() With an Array?
You use an array to implement a stack but the array does not have push or pop methods as part of the array class More on reddit.com
🌐 r/learnprogramming
14
0
September 6, 2017
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
🌐
Java array pop
regealpine.mystrikingly.com › blog › java-array-pop
Java array pop
November 1, 2023 - The () method in Java is used to pop an element from the stack. var myFish = Ĭonsole.log(myFish) // Ĭonsole.log(popped) // 'sturgeon' Specifications Specification · The following code creates the myFish array containing four elements, then ...
🌐
HowToDoInJava
howtodoinjava.com › home › data structure › stack using array
Java Stack Implementation using Array
March 31, 2023 - import java.util.Arrays; public class Stack { private int maxSize; private Object[] stackArray; private int top; public Stack(int size) { maxSize = size; stackArray = new Object[maxSize]; top = -1; } public void push(Object value) { if (isFull()) { System.out.println("Stack is full. Cannot push element."); return; } top++; stackArray[top] = value; } public Object pop() { if (isEmpty()) { System.out.println("Stack is empty.
🌐
TutorialsPoint
tutorialspoint.com › java › util › arraydeque_pop.htm
Java ArrayDeque pop() Method
The Java util ArrayDeque pop() method pops an element from the stack represented by this deque. Essentially it removes the first element of the ArrayDeque object. Following is the declaration for java.util.ArrayDeque.pop() method NA This method
🌐
GeeksforGeeks
geeksforgeeks.org › java › arraydeque-pop-method-in-java
ArrayDeque pop() Method in Java - GeeksforGeeks
December 10, 2018 - Array_Deque.pop() Parameters: The method does not take any parameters. Return Value: This method returns the element present at the front of the Deque. Exceptions: The method throws NoSuchElementException is thrown if the deque is empty. Below programs illustrate the Java.util.ArrayDeque.pop() method: Program 1:
Find elsewhere
🌐
Educative
educative.io › answers › what-is-the-arraydequepop-method-in-java
What is the ArrayDeque.pop method in Java?
From lines 5 to 7: We use the add() method of the arrayDeque object to add three elements ("1","2","3") to dequeu. In line 10: We use the pop() method of the arrayDeque object to get and remove the first element.
🌐
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 - Create a LinkedListlisand add elements of integer type using the push() method. Then, print the LinkedListand remove the elements using the pop() method. On executing the code, LinkedList before removing elements and after removing elements ...
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
AlgoCademy
algocademy.com › link
Array Push in Java | AlgoCademy
List<String> list1 = new ArrayList<>(List.of("A", "B")); List<String> list2 = new ArrayList<>(List.of("C", "D")); list1.addAll(list2); // list1 is now ["A", "B", "C", "D"] This method is useful when you need to merge two lists. Here is a complete example demonstrating the use of the .add() method: import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { // Initialize an ArrayList with some elements List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3)); // Append elements to the ArrayList numbers.add(4); numbers.add(5); // Print the ArrayList System.out.println(numbers); // Output: [1, 2, 3, 4, 5] } }
🌐
LinkedIn
linkedin.com › all › engineering › programming
How can you implement a stack using an array in Java?
January 18, 2024 - To push an element to the stack, ... = element; To pop an element from the stack, you need to return the element at the top index and decrement the top by one, for example, return array[top--]; However, you also need to check ...
🌐
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 is a mutating method. It changes the length and the content of this. In case you want the value of this to be the same, but return a new array with the last element removed, you can use arr.slice(0, -1) instead.
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.

🌐
Baeldung
baeldung.com › home › java › java array › removing the first element of an array
Removing the First Element of an Array | Baeldung
April 22, 2025 - First of all, removing an element of an array isn’t technically possible in Java.
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 - public E pop(): Removes and returns the first element of the list. ... import java.util.LinkedList; class LinkedListPopDemo{ public static void main(String[] args) { // Create a LinkedList of Strings LinkedList<String> list = new LinkedList<String>(); // Add few Elements list.add("Jack"); ...
🌐
Stack Abuse
stackabuse.com › remove-element-from-an-array-in-java
Remove Element from an Array in Java
December 16, 2021 - In this tutorial, we'll showcase examples of how to remove an element from an array in Java using two arrays, ArrayUtils.remove(), a for loop and System.arraycopy().