Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advance for reference variables?

I am trying to understand the difference between Object with primitive variables when using them as parameters in a method.

There are some examples using reference variables:

public class Test1 {
    public static void main(String[] args) {
        int[] value = {1};
        modify(value);
        System.out.println(value[0]);
    }

    public static void modify(int[] v) {
        v[0] = 5;
    }
}

result: 5

public class Test2 {

    public static void main(String agrs[]) {
        Integer j = new Integer(1);
        refer(j);
        System.out.println(j.intValue());
    }

    public static void refer(Integer i) {
        i = new Integer(2);
        System.out.println(i.intValue());
    }
}

result: 2 | 1

So what is different in here?

like image 676
Thangnv Avatar asked Jul 07 '26 14:07

Thangnv


1 Answers

In java array is primitive type.and Integer is Object type.

For primitives it is pass by value the actual value (e.g. 3)

For Objects you pass by value the reference to the object.

In first example, you are changing value in array.

while in other example , you are changing reference of i to other memory location where object value is 2. when returning back to main function, as you are not returning value. its reference scope limited to "refer" method only.

like image 153
swapy Avatar answered Jul 09 '26 05:07

swapy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!