• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem in Arrays passing.

 
Himanshu Gupta
Ranch Hand
Posts: 598
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Output:


I am not able to understand that why the array is null here??
 
Stephan van Hulst
Bartender
Pie
Posts: 6114
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java passes all arguments by value.

This means that the arr variable in your initArray method will refer to the same array that you pass to it in your main method, but it is a different variable from the arr variable in your main method.
You essentially pass the value null to it, then you assign a new array to arr in initArray, which is a different variable from arr in your main method, so nothing happens to your main method variable.

Instead, you could do something like this:
 
Himanshu Gupta
Ranch Hand
Posts: 598
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What I wanted to do is to pass the null reference as an argument and let the other function assign a new array which will be used by the calling function.

As Java is pass by reference I was thinking that the reference is being passed and the same reference is used to assign a new Object if int array.
 
Stephan van Hulst
Bartender
Pie
Posts: 6114
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Himanshu Gupta wrote:As Java is pass by reference I was thinking that the reference is being passed and the same reference is used to assign a new Object if int array.


No, Java uses pass by value in all cases.
 
Rob Spoor
Sheriff
Pie
Posts: 20610
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://www.coderanch.com/how-to/java/CallByReferenceVsCallByValue
 
VennkataReddy Kv
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
plese go through attached file
Code.png
[Thumbnail for Code.png]
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is that relevant? I'm not sure of the point you're trying to make.

Remember Java passes references by value.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49796
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree it is by no means clear what you meant by that diagram. But I think you are mistaken there, if you think you can replace the null from a method call.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic