Switch to full style
General Java code examples
Post a reply

Passing arrays as function parameter in java

Sun Aug 09, 2009 10:29 pm

You should be able to see the difference between passing the array as parameter in following two cases :
1. Assigning objects to the array of reference before the calling of function: .

Code:
  public static void main(String[] args) {
  byte[] arr=new byte[3];
 byte[] x=     calc(arr);
       // in this case x = arr ( not null);
    }

    public static  byte[] calc (byte[] arr)
    {
        //do something here. 
        return arr; 
        
    
} 

2. Assigning objects to the array of references in the called of function:
Code:

     public static void main
(String[] args) {
        byte[] arr = null;
        byte[] x = calc(arr);
      // in this case arr = null

        System.out.println(x.length);
        System.out.println(arr);
    }

    public static byte[] calc(byte[] arr) {
        arr = new byte[3];
        //do something here.
        return arr;

    }
 


The output of the second code snippet is :
Code:
3
null


You notice that the reference "arr" is still null in the main function



Re: Passing arrays as function parameter in java

Sun Oct 21, 2012 1:38 pm

updated.

Post a reply
  Related Posts  to : Passing arrays as function parameter in java
 Passing Enum as Type Parameter to method     -  
 JSP Passing Arrays to Methods     -  
 Passing an Argument to a Function by Value     -  
 Passing Pointers to function example     -  
 passing string value from java to .exe file     -  
 Java script time parameter     -  
 Arrays in java     -  
 Comparing Arrays in java     -  
 creating arrays in java     -  
 Multidimensional arrays in Java     -  

Topic Tags

Java Arrays