• Post Reply Bookmark Topic Watch Topic
  • New Topic

Having trouble with passing parameters to methods  RSS feed

 
Angela Li
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I can't get b to print out to be 32 and I keep getting 16.



I also tried this but it also didn't work.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12562
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All variables in java are 'pass by value'. So when you pass b into your method, you pass in the value 16, which then gets assigned to your 'a'. So 'b' is pointing to one spot in memory that holds the value 16, and a is pointing to a DIFFERENT spot that also holds 16.

you do a *= 2;, which does double what a is pointing to, but the value b points to is untouched.
 
Praveen Kumar M K
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Angela,

Please go through the link that Henry has provided, that should solve your problem.

For the specific example that you have posted, instead of passing objl.b, try and see what happens when you pass objl itself.

 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Angela Li wrote:I also tried this but it also didn't work...

Try this instead:Lessons:
1. Methods, in order to be useful, generally return something, so don't use void unless you know it's correct (eg, for a 'setter' method, or for main() itself).
2. Resist the urge to make everything static.
3. Make instance fields private unless you have a good reason not to.
4. It may be a bit early yet, but try to get into the habit of writing classes, not main() methods.
5. Read what the others have already told you about 'pass by value'.

HIH

Winston
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!