File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Problem in Arrays passing. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Problem in Arrays passing. " Watch "Problem in Arrays passing. " New topic
Author

Problem in Arrays passing.

Himanshu Gupta
Ranch Hand

Joined: Aug 18, 2008
Posts: 598



Output:


I am not able to understand that why the array is null here??


My Blog SCJP 5 SCWCD 5
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  17

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

Joined: Aug 18, 2008
Posts: 598

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

Joined: Sep 20, 2010
Posts: 3647
    
  17

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

Joined: Oct 27, 2005
Posts: 19718
    
  20

http://www.coderanch.com/how-to/java/CallByReferenceVsCallByValue


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
VennkataReddy Kv
Greenhorn

Joined: Mar 28, 2011
Posts: 3
plese go through attached file


[Thumbnail for Code.png]

Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4420
    
    8

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

Joined: Oct 13, 2005
Posts: 39393
    
  28
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem in Arrays passing.