Reputation: 15911
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 :
Is it possible to return different types of return value in java based on conditions ??? and
Is there a better workaround to solve such problem instead of what i am trying in my code??
P.S : Please don't go on my Rep before answering, m hell Noob in java
Upvotes: 1
Views: 170
Reputation: 62864
No, you can't return different types of object from methods (unless they have a common superclass, in which case this is possible).
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
Reputation: 189
You can use Integer
as return type and return null
when stack is empty.
Thanks to @LuiggiMendoza
Upvotes: 2
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
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