NoobEditor
NoobEditor

Reputation: 15911

Return bool or integer from a method depending on condition

The very basic program of pop'ng a value from Stack in DS :

public int pop()
{
    if(!isEmpty())
    {
        int pop_val = myArray[topIndex];
        topIndex--;
        return pop_val;
    }
    else
    {
        System.out.println("Stack is empty");
        System.exit(0); /* stop the program execution*/
        return 4; /* did this just to avoid the error*/
    }
}

Problem : As you can see,method is supposed to return an int type value but i just want to print or return a false if stack is empty.

Question :


P.S : Please don't go on my Rep before answering, m hell Noob in java

Upvotes: 1

Views: 170

Answers (4)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

  1. No, you can't return different types of object from methods (unless they have a common superclass, in which case this is possible).

  2. If I were you, I would throw a custom Exception when the stack is empty:

For example:

public int pop() throws EmptyStackException {
 ...
}

Note: If you don't want to use Exception(s), you can define an invalid return value, for example -1.

public int pop() {
    ...

    return -1; /* did this just to avoid the error*/
}

Upvotes: 4

Sswater Shi
Sswater Shi

Reputation: 189

You can use Integer as return type and return null when stack is empty.

Thanks to @LuiggiMendoza

Upvotes: 2

Tyler
Tyler

Reputation: 18177

It is not possible for a method to have different return types.

You should break your functionlity into 2 seperate methods: 1) check if the list is empty, 2) pop from the list.

public boolean hasContent () {
    //Check to see if there is something to pop()
}

public int pop() {
    //Pop off the stack
    //Throw an error or return some sort of default empty value if there is nothing to pop
}

...

//usage
if(stack.hasContent()) {
  stack.pop()
}

Upvotes: 0

Maroun
Maroun

Reputation: 95978

I would throw an exception to indicate that the stack is empty, however, if you don't want to do that, you can return 0 and it'll be the caller responsibility to arise an error or whatever he wants if the stack is empty.

Upvotes: 2

Related Questions