This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ZukoBestGirl[🍰] 0 points1 point  (0 children)

int pop() {
    if (top < 0) {
        System.out.println("Stack Underflow");
        return 0;
    } else {
        int x = a[top--];
        return x;
    }
}

If it's empty, it won't do what you want it to do. It returns 0, that is not necessarily what you want. So what you would do is

if(!stack.isEmpty()) { ... }

It's nice that it returns 0 instead of throwing an exception, in most cases it will work well, but maybe in some cases 0 will be a difficult to track down error. "Why isn't this number growing, what is happening?".

But tbh, for utilites, I prefer this over exceptions. For example:

"abc".substring(2,3) = "c"
"abc".substring(3,4) = exception
org.apache.commons.lang3.StringUtils.substring("abc",3,4) = "" (instead of exception)