return : Java Glossary

return
There are three general ways to get information computed inside a method back to the caller, and one extra way that only works if caller and callee are in the same class:
  1. You can return one and only one value to the caller (primitive or object) with return. Java allows multiple inputs to a method but only one output. This restriction is very deeply burned into both the design of Java
    return a+b;
  2. Hide the values you want to return inside objects that were passed as parameters. e.g.
    void myMethod( Thing t )
       {
       t.a = 42;
       return;
       }
    // end myMethod
  3. hide them inside an object (possibly an array) created inside the caller, and return that object, e. g.
    int[] myMethod()
       {
       // ...
       int[] r = new int[3];
       r[0] = ans0;
       r[1] = ans1;
       r[2] = ans3;
       return r;
       }
    // end myMethod
  4. If caller and callee belong to the same class, there is another technique which must be used with care. Hide the information in instance or static variables that both caller and callee can access. There is a way around this same class restriction, but it would generally be considered poor programming form, so I won’t corrupt you with the details.
The one thing a method cannot do is make the caller’s parameter variables change value, or point to different objects, the way you can in Pascal or C++. If you change a parameter’s value inside a called method, you only change the callee’s local copies.

CMP homejump to top You can get the freshest copy of this page from: or possibly from your local J: drive (Java virtual drive/mindprod.com website mirror)
http://mindprod.com/jgloss/return.html J:\mindprod\jgloss\return.html
logo
Please email your , letters to the editor, errors, omissions, typos, formatting errors, ambiguities, unclear wording, broken/redirected link reports, suggestions to improve this page or comments to Roedy Green : feedback email. If you want your message, your name or email kept confidential, not considered for public posting, please explicitly specify that. Unless you state otherwise, I will treat your message as a letter to the editor that I may or may not publish in the feedback section. After that, it will be too late to retract it. If you disagree with something I said, please quote it and cite the web page where you found it, tell me why you think it is wrong, and, if possible, provide some supporting evidence. Threatening to kill me or spouting obscenities has yet to persuade me to change my mind.
mindprod.com IP:[65.110.21.43]
view BlogYour face IP:[38.107.179.214]
You are visitor number 61,357.