Java object references passed-by-value

mail@pastecode.io avatar
unknown
java
2 years ago
1.9 kB
3
Indexable
Never
import java.util.Arrays;

public class MyClass {
    
    public static int[] additionBroken(int[] arr, int add) {
       
       // modify the array that the reference is pointing to
       for (int i=0; i<arr.length; i++) {
           arr[i] += add;
       }
       
       // return reference to same array
       return arr;
    }
    
    public static int[] additionCorrect(int[] arr, int add) {
        
       // create new array object
       int[] result = new int[arr.length];
       
       // fill the new array object
       for (int i=0; i<2; i++) {
           result[i] = arr[i] + add;
       }
       
       // return reference to new object
       return result;
    }
    
    public static void printArr(int[] arr) {
        System.out.println(Arrays.toString(arr));
    }
    
    public static void main(String[] args) {
        // Simple signal int array [0, 5]
        int [] signal = new int[2];
        signal[0] = 0;
        signal[1] = 5;
        System.out.println("signal:");
        printArr(signal);
    
        // broken
        int[] lowSignal = additionBroken(signal, -3);
        
        //0 - 3 = -3, 5 - 3 = 2 
        System.out.println("lowSignal:");
        printArr(lowSignal);
      
        //pass reference to same signal array
        int[] highSignal = additionBroken(signal, +1);
        
        //-3 + 1 = -2, 2 + 1 = 3
        System.out.println("highSignal:");
        printArr(highSignal);
        
        // correct
        int [] signal2 = new int[2];
        signal2[0] = 0;
        signal2[1] = 5;
        System.out.println("signal2:");
        printArr(signal2);
        
        int[] lowSignal2 = additionCorrect(signal2, -3);
        
        System.out.println("lowSignal2:");
        printArr(lowSignal2);
        
        int[] highSignal2 = additionBroken(signal2, +1);
        
        System.out.println("highSignal2:");
        printArr(highSignal2);
        
    }
}