Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.help > #1095

Re: Trouble with updating reference variables through method calls

From Lew <lewbloch@gmail.com>
Newsgroups comp.lang.java.help
Subject Re: Trouble with updating reference variables through method calls
Date 2011-09-22 18:01 -0700
Organization http://groups.google.com
Message-ID <25911727.1362.1316739702916.JavaMail.geo-discussion-forums@prfb12> (permalink)
References <3bf29bca-0e7e-4104-8b55-2e4589dd2ce9@x32g2000prf.googlegroups.com>

Show all headers | View raw


Fred wrote:
> If this sort of code actually works (which I doubt), I might have to
> post some of my actual code for help.

Your code won't even compile.  Post a short, self-contained compilable example
http://sscce.org/
so we can duplicate your difficulty.

> Why is foo1 updated in updateFoo but not in main() (if choice is 1)?
> 
> class Bar {
>     private static void getNewFoo() {
>         Foo foo = new Foo();
>         return foo;

You can't return a value when the return type is 'void'.

>     }
> 
>     private static void updateFoo(Foo foo1, Foo foo2, Foo foo3) {
>         int choice = getChoice();
>         ...
>         if (choice == 1)
>             foo1 = getNewFoo();

Put braces around the statement body of your 'if'.

When you change the pointer value of 'foo1', a method argument, you change it only within the method.  The caller cannot see that change.  Whatever the caller had for the first argument to 'updateFoo' will still be whatever it was just before the call.

>         ...
>     }
> 
>     public static void main(String[] args) {
>         Foo foo1 = new Foo();
>         Foo foo2 = new Foo();
>         Foo foo3 = new Foo();
>         updateFoo(foo1, foo2, foo3);
>     }

-- 
Lew

Back to comp.lang.java.help | Previous | NextPrevious in thread | Next in thread | Find similar


Thread

Trouble with updating reference variables through method calls Fred <albert.xtheunknown0@gmail.com> - 2011-09-22 17:42 -0700
  Re: Trouble with updating reference variables through method calls Lew <lewbloch@gmail.com> - 2011-09-22 18:01 -0700
  Re: Trouble with updating reference variables through method calls Eric Sosman <esosman@ieee-dot-org.invalid> - 2011-09-22 22:47 -0400
  Re: Trouble with updating reference variables through method calls Roedy Green <see_website@mindprod.com.invalid> - 2011-09-22 20:29 -0700
  Re: Trouble with updating reference variables through method calls Roedy Green <see_website@mindprod.com.invalid> - 2011-09-22 20:33 -0700
  Re: Trouble with updating reference variables through method calls Roedy Green <see_website@mindprod.com.invalid> - 2011-09-22 20:34 -0700
  Re: Trouble with updating reference variables through method calls Travers Naran <tnaran@gmail.com> - 2011-09-22 21:27 -0700

csiph-web