• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Call by Value

 
David Houghton
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The question relates to java basics, im currently studyiung towards my SCJP cert. This is about a passage ive read in a book that doesnt make sense. Its not about the actual cert so ive put it here in the begginer section. The passage states:


If the argument passed into the method is a primitve type, it is impossible in Java for the method to alter the value of the original primitive (SCJP Study Guide, Richard F Raposa, page37, passing primitives vs passing references).

The section is on Call by Value.

My question is, doesnt the code i have given below make this passage incorrect?

 
Gavin Tranter
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In what way do you think that your example makes the statement about how Java passes primitive types incorrect?
 
David Houghton
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you comile and run the code, the following print statment show that the x value has changed from 0 to 5 due toi being changed by the method



 
David Houghton
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the netbeans output

 
Fred Hamilton
Ranch Hand
Posts: 684
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
look at it this way. if you had int n=5; in your main method, and you passed n instead of 5, e.g. m.setX(n);

then no matter what happens in the method setX, n would still be equal to 5 in your main method. That is what is meant by "the method can't change the the value of the original primitive"
 
fred rosenberger
lowercase baba
Bartender
Posts: 12143
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you are not changing the value of the passed parameter. you change the value of a class variable. Try changing your code to something like this:



Here, I pass temp into a method, and change it's value. But back in main, themp says as 5 (assuming i wrote this correctly - I didn't test or verify it even compiles).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic