It's not a secret anymore!*
The moose likes Beginning Java and the fly likes Call by Value Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Call by Value" Watch "Call by Value" New topic
Author

Call by Value

David Houghton
Greenhorn

Joined: Jan 11, 2009
Posts: 19
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

Joined: Jan 01, 2007
Posts: 333
In what way do you think that your example makes the statement about how Java passes primitive types incorrect?
David Houghton
Greenhorn

Joined: Jan 11, 2009
Posts: 19
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

Joined: Jan 11, 2009
Posts: 19
This is the netbeans output

Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
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

Joined: Oct 02, 2003
Posts: 11408
    
  16

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).


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Call by Value