Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey,
i just started with java and i'm playing around with arrays wich are the current step in the tutorial.
What i dont understand is why this:
int a = 7;
int b = a;
b = a + 3;
System.out.println(a);

prints 7 while this:
int[] c = new int[1];
c[0] = 7;

int[] d;
d = c;
d[0] = c[0] + 3;
System.out.println(c[0]);

prints 10.

Hope this isn't a to self evident question to ask.
Posted
Comments
Kenneth Haugland 20-Sep-15 15:09pm    
One makes a copy and the other don't, and functions as a pointer instead. Not a Java expert, but normally it has to do with the initialization of variables.
Mohibur Rashid 20-Sep-15 19:03pm    
in case of array, d is referencing c; so writing c[0] = c[0] + 3 is equivalent

1 solution

The best way to understand this is to run it through a debugger and follow exactly what happens.
int[] c = new int[1];
c[0] = 7;

This declares an array variable c, assigns it an array of one element, and puts the value 7 into the single element.
int[] d;
d = c;

This declares an array variable d, cities the array that c "points at" into it. At this point, c and d both refer to the same array of data, in the same way as "my car" and "my wife's car" both refer to the same vehicle because we only have one between us.
d[0] = c[0] + 3;
System.out.println(c[0]);

So since they are both the same array, you retrieve a value, add 3, and put it back where it came from. To continue the car metaphor, if I put my wallet in the glove box of "my car", my wife can open the glove box of "her car", find my wallet, and spend all my money!
 
Share this answer
 
Comments
Kenneth Haugland 21-Sep-15 2:39am    
5'ed, but I'm starting to dislike your wife a little :laugh:
OriginalGriff 21-Sep-15 3:02am    
Being married is sometimes like being gently mugged on a regular basis :sigh:
Kenneth Haugland 21-Sep-15 3:42am    
I have heard that a divorce is much more muggy (if that's a word)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900