• Post Reply Bookmark Topic Watch Topic
  • New Topic

parameter passing with arrays  RSS feed

 
Pooja Pawar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



output: i = 1  iArr[0] = 2

Could anyone please explain why i =1 whereas iArr[0]=2?
 
Liutauras Vilda
Sheriff
Posts: 4928
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

Because Java is pass-by-value and the value passed in and changed inside does not affect original value.
With passed reference type value is, that changed value reflects in an array elements for instance, but still, you can't re-assign original reference variable where it is pointing to. i.e.:

So, iArr as it was pointing to an array it is still pointing, even though you have n = null.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pooja Pawar wrote:
Could anyone please explain why i =1 whereas iArr[0]=2?


The coderanch tutorial on parameter passing may be a good place to start here...

http://javaranch.com/campfire/StoryPassBy.jsp

Henry
 
Knute Snortum
Sheriff
Posts: 4287
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The i variable is type int, so it is a primitive, not an object reference.  Since Java is pass-by-value, the method invocation will "look" like this:
The value of i is all that gets passed.

With objects it get trickier.  We tend to think of i in int[] i = new int[3]; as an object, but in fact i holds an object reference.  It is this reference that gets copied and passed to the method:
So now n holds the same reference to an object as i does.  Therefore changes made to n will be reflected in i.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!