Wednesday, February 26, 2014

Return an array from method

This example show how to return an array from method. And also show that we can change the source array inside method.

Return an array from method
Return an array from method

package java_array;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class Java_Array {

    public static void main(String[] args) {
        
        int orgInt = 5;
        float returnFloat = intMethod(orgInt);
        System.out.println("original int no changed: " + orgInt);
        System.out.println("float return from method: " + returnFloat);
        
        int[] orgArray = new int[]{1, 2, 3, 4, 5};
        
        System.out.println();
        System.out.println("Original array defore calling method");
        for(int i=0; i<orgArray.length; i++){
            System.out.println(orgArray[i]);
        }
        
        float[] returnArray = arrayMethod(orgArray);
        
        System.out.println();
        System.out.println("Original array changed in method");
        for(int i=0; i<orgArray.length; i++){
            System.out.println(orgArray[i]);
        }
        
        System.out.println();
        System.out.println("Array of float returned from method");
        for(int i=0; i<returnArray.length; i++){
            System.out.println(returnArray[i]);
        }
        
    }
    
    static private float[] arrayMethod(int[] src){
        float[] result = new float[src.length];
        
        for(int i=0; i<src.length; i++){
            result[i] = (float)src[i];
            src[i] = src[i] * src[i];
        }
        
        return result;
    }
    
    static private float intMethod(int src){
        float result = src;
        src = src * src;
        return result;
    }
}

No comments:

Post a Comment