Implementing two stacks using single array in java Please review the code

package com.gmail.practice;

import java.util.Arrays;

public class StacksForTwo {

    int size;
    int[] stack;
    int top1;
    int top2;

    public StacksForTwo(int arraysize)
    {
        size = arraysize;
        stack = new int[size];
        top1 = -1;
        top2 = size;        
    }

    public void push1(int x)
    {
        if(top1 &lt; top2-1)
        {
        top1++;
        stack[top1] = x;        
        }else{
            System.out.println("stackoverflow");
        }
    }

    public void push2(int y)
    {
        if(top1 &lt; top2-1)
        {
            top2--;
            stack[top2] = y;
        }else{
            System.out.println("stack overflow");
        }
    }

    public void pop1()
    {
        if(top1 &gt;= 0)
        {
            top1--;
            System.out.println("The popped out number is"+" "+stack[top1+1]);
        }else{
            System.out.println("stack underflow");
        }
    }

    public void pop2()
    {
        if(top2 &lt; size)
        {
            top2++;
            System.out.println("The popped out number is"+" "+stack[top2+1]);
        }else{
            System.out.println("stack underflow");
        }
    }

    public void display()
    {
        System.out.println(Arrays.toString(stack));
    }

    public static void main(String[] args)
    {
        StacksForTwo sft = new StacksForTwo(10);
        sft.push1(4);
        sft.push1(5);
        sft.push1(3);
        sft.push1(2);
        sft.push2(6);
        sft.push2(4);
        sft.display();
        sft.push2(8);
        sft.push1(2);
        sft.push2(6);
        sft.push2(4);
        sft.push2(8);
        sft.display();
    }
}
I would go for

interface Stack {
    boolean isEmpty();
    int pop();
    void push(int x);
}


And then make a class providing two Stacks.

Also create a counter to detect when both stacks are full. This can be done with an AtomicInteger (thread-safeness) counting the free array slots.

public class StackPair {
    public final Stack firstStack = new Stack { ... };
    public final Stack secondStack = new Stack { ... };
    public StackPair(int capacity) { ... }




In StackPair the single array and an AtomicInteger freeEntries. In both Stack implementations access to the array and freeEntries.