Search code examples
javastack-overflow

Getting barcode - Exception in thread "main" java.lang.StackOverflowError


public static void main(String[] args) {

    CashRegister myCashRegister = new CashRegister();

    Item item = myCashRegister.getItem(123456);



public class CashRegister {
    public Item getItem(int barcode) {
        return this.getItem(barcode);
    }



public class Item {

    public int getBarcode(){
        return barcode;
    }

I am creating an item object in main and trying to get the item's barcode through a Cash Register class. I end up getting "Exception in thread "main" java.lang.StackOverflowError".

I do have a getBarcode method in the item class, but kept getting errors because barcode is an int, and so I cannot return an int for the Item getItem method.

Please put me in the right direction towards getting the item's barcode. Thank you.


Solution

  • You have programmed an endless loop.

    public Item getItem(int barcode) {
        return this.getItem(barcode);
    }
    

    Here you are calling the same method again and again...