Could someone please give me some sample code that uses an output parameter in function? I’ve tried to Google it but just found it just in functions. I’d like to use this output value in another function.
The code I am developing intended to be run in Android.
Java passes by value; there’s no
outparameter like in C#.You can either use
return, or mutate an object passed as a reference (by value).Related questions
? (NO!)
Code sample
See also
As for the code that OP needs help with, here’s a typical solution of using a special value (usually
nullfor reference types) to indicate success/failure:Instead of:
Use a
Stringreturn type instead, withnullto indicate failure.This is how
java.io.BufferedReader.readLine()works, for example: it returnsinstanceof String(perhaps an empty string!), until it returnsnullto indicate end of “search”.This is not limited to a reference type return value, of course. The key is that there has to be some special value(s) that is never a valid value, and you use that value for special purposes.
Another classic example is
String.indexOf: it returns-1to indicate search failure.A more general solution
If you need to return several values, usually they’re related in some way (e.g.
xandycoordinates of a singlePoint). The best solution would be to encapsulate these values together. People have used anObject[]or aList<Object>, or a genericPair<T1,T2>, but really, your own type would be best.For this problem, I recommend an immutable
SearchResulttype like this to encapsulate thebooleanandStringsearch results:Then in your search function, you do the following:
And then you use it like this:
If you want, you can (and probably should) make the
finalimmutable fields non-public, and usepublicgetters instead.