This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes can anybody explain this?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "can anybody explain this??" Watch "can anybody explain this??" New topic
Author

can anybody explain this??

saritha cheler
Greenhorn

Joined: Nov 15, 2000
Posts: 13
1. public class PrimitiveReferences{
2. public static void main(String args[]){
3. int[] muValue = {1};
4. modifyIt(myValue);
5. System.out.println("myValue contians" + myValue[0]);
6. }
7. public static void modifyIt(int[] value){
8. value[0]++;
9. }
10.}

At line 5 it prints 2. How can it be possible when the incrementation of the value is till that method. It should print 1 at line 5. Can anybody explain this y it prints 2 at line 5.

------------------
thanks
saritha.


thanks<BR>saritha.
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
I'm not sure of what your question is. You pass the array to a method, increment one of the elements, and then print off that elelment back in main. This is all perfectly legal and valid.
By the way, you have a typo in your code, you have muValue instead of myValue.
Bill
Ishaan Mohan
Ranch Hand

Joined: Jan 20, 2001
Posts: 115
Hi,
Arrays are objects, meaning that programs deal with references to arrays, not with arrays themselves. What gets passed into a method is a copy of reference to an array. It is therefore possible for a called method to modify the caller's array.
At line 4 you are calling a method which increments the value from 1 to 2 hence on line 5 you are getting output as 2.
Sandy Lee
Greenhorn

Joined: Jan 18, 2001
Posts: 18
This because array is a object. You are passing a reference to the Array object and then modifying its value.
Had it just been an int and not an array of int, then you would see the results you are looking for.
That is not change in value.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: can anybody explain this??