posted 8 years ago
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?
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?


David Houghton
Greenhorn
Posts: 19
posted 8 years ago
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"
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"
posted 8 years ago
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).
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

Don't get me started about those stupid light bulbs. |