Why is this happening on my code although I did not return any value from a method?

Tags: ,



I wrote some Java code;

int quantity = 0;

public void submitOrder(View view) {
    displayMessage(createOrderSummary());
}

public void increment(View view) {
    quantity = quantity + 1;
    display(quantity);
}

public void decrement(View view) {
    quantity = quantity - 1;
    display(quantity);
}

private String createOrderSummary() {
    String message = "Quantity : " + quantity;
    return message;
}

This code is working fine. When I press + and – buttons on app, it is executing increment and decrement methods. But in those methods, I used void. Which I learned that means “no return” on that method.

So, how can this code works as showing the quantity variable changed; although it was changed in a method which has no return statement?

I think it should show quantity as 0, because the changed quantity values were not returning from those methods. Where am I wrong?

Answer

Actually not returning the integer doesn’t mean that it’s not applying the change (e.g: incrementing quantity = quantity + 1; )

void means that no value will be returned to use in the place where the function is called (for an e.g in a different class). But if you call it, it will still execute the code inside it.



Source: stackoverflow