returning null instead of int
Hi,
I have the following code. The point is to test returns.
Code Java:
public class objects
{
public static void main(String[]args)
{
int x = 0;
}
public int testZero(int x)
{
if (x == 0)
{
System.out.println(x);
return ;
}
else
{
return x;
}
}
}
As is, I get a "missing return value" error from the compiler for the line "return ;", line 13. If I remove that statement, I get "missing return statement".
How should/could I handle this? If my method has a return type, MUST I return a value of that type? Is there a way not to do that?
Thank you,
Mike
Re: returning null instead of int
an int can never have a null value because it's a Java primitive. However, there are wrapper classes for primitives which can be null.
ex.:
Code java:
// didn't test run this, hopefully it works
public Integer testZero(int x)
{
if(x == 0)
{
return null;
}
else
{
return x;
}
}
Every execution path must end in either a return value or throwing something (usually an exception). There are a few odd cases where a method doesn't terminate normally (for example, System.exit()), but these are rare.
Why not use booleans? These are meant to hold true/false values, ideal for answering yes/no type questions.
Code java:
public boolean isZero(int x)
{
if(x == 0)
{
return true;
}
else
{
return false;
}
}
Re: returning null instead of int
Hello Mike!
Quote:
Originally Posted by
youngstorm
How should/could I handle this? If my method has a return type, MUST I return a value of that type? Is there a way not to do that?
Yes, you are correct. You must return a value of that type. There is no way you can avoid that - as far as I know.
A common way to handle this situation is to have some "default" return values. For example, return 0 for default or -1 for an error. Then in your program you can check if these values are returned and handle them accordingly.
Hope this helps.
Re: returning null instead of int
Thanks to both of you for your help. This is the info I was looking for. Also, glad to know about the wrapper classes, that will do what I was hoping to do. Again, no special reason; I'm just playing and learning. :)
Thanks again guys.
--- Update ---
How do I mark this thread as solved?
Re: returning null instead of int
At the top, under Thread Tools > Mark this thread as solved
Re: returning null instead of int