Thangnv
Thangnv

Reputation: 815

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?

Upvotes: 2

Views: 153

Answers (4)

Maroun
Maroun

Reputation: 95958

Recall that the array references are passed by value. The array itself is an object, and that's not passed at all (That means that if you pass an array as an argument, your'e actually passing its memory address location).

In modify() method, you're assigning 5 to the first place in the array, hence, changing the array's value. So when you print the result, you get: 5 because the value has been changed.

In the second case, you're creating a new Object of type Integer locally. i will have the same value when you exit the method refer(). Inside it you print 2, then you print i, which is 1 and hence change doesn't reflect.

Upvotes: 5

rocketboy
rocketboy

Reputation: 9741

v[0] = 5, is like saying Get 0th element of current v's reference and make it 5.
i = new Integer(2), is like saying change i to 2's Integer object reference

In one case you are changing the internal values via the reference and in latter you are changing the reference itself.

Upvotes: 3

swapy
swapy

Reputation: 1616

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.

Upvotes: 5

user207421
user207421

Reputation: 310884

The difference here is that they are different.

In your first example you are passing the argument to another method, which is modifying one of its elements, which is visible at the caller. In the second case you are assigning the variable to a new value, which isn't visible at the caller, because Java has pass-by-value semantics.

NB 'Primary variable' has no meaning in Java.

I don't know what the word 'advance' in your title has to do with anything.

Upvotes: 2

Related Questions