What will be displayed after executing the following code?

class Test {
    public static void main(String[] args){
        int x = 1;
        Integer y = new Integer(x);
        int [] z = {x};
        
        func(x, y, z);
        
        System.out.print(x);
        System.out.print(y);
        System.out.println(z[0]);
    }
    
    static void func (int x, Integer y, int[] z) {
        x++;
        y++;
        z[0]++;
    }
}
Explanation

Since the transmission of the parameters in the method is carried out by value, then:
- the variable x stores the same number;
- the variable y refers to the same object;
- the variable z refers to the same massif,
same as external variables.

Changing the value of x does not affect the value of the external variable.
The object of the Integer type are immutable, so after the operation y++ the variable y will refer to the new object (with a larger value), and the original object will remain intact.
Reference to an array allows you to freely modify the values ​​of the array elements.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback