File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "can anybody explain this??" Watch "can anybody explain this??" New topic

can anybody explain this??

saritha cheler

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

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.


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.
Ishaan Mohan
Ranch Hand

Joined: Jan 20, 2001
Posts: 115
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

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.
subject: can anybody explain this??
It's not a secret anymore!