# ¿Values by Reference? I dont understand...

Printable View

• 02-22-2012, 03:08 AM
Daxan
¿Values by Reference? I dont understand...
First, sorry about my english :).

I have a question:

I have:

[...]
static long tiempo = 0;
public static void main(String[] args)
{
int test2 [] = {435,544,33,22,4,23,54,12323,5,3,0,121,4,65};
ordenar_array_Burbuja(test2);
mostrar_array(test2);
}

public static void ordenar_array_Burbuja(int array_a_ordenar[]) // Función que devuelte un array ordenado
{
mostrar_array(array_a_ordenar);
tiempo = System.currentTimeMillis();
int n = array_a_ordenar.length;
for (int pass=1; pass < n; pass++) { // count how many times
// This next loop becomes shorter and shorter
for (int i=0; i < n-pass; i++) {
if (array_a_ordenar[i] > array_a_ordenar[i+1]) {
// exchange elements
int temp = array_a_ordenar[i]; array_a_ordenar[i] = array_a_ordenar[i+1]; array_a_ordenar[i+1] = temp;
}
}
}
long total = 0;
total = System.currentTimeMillis()-tiempo;
System.out.println("He tardado "+ total +" en terminar");
mostrar_array(array_a_ordenar);
}
[...]

If I invoke "ordenar_array" and then I print "test2", the array dont have the initial values (435,544,33,22,4,23,54,12323,5,3,0,121,4,6), the array is sorted. ¿why? I dont return de array sorted to test2.

This example:

public class Test{
public static void sum (Integer i){

int val = i;
val+=4;
i = val;

}

public static void main (String args[]){

Integer i = new integer (5);
sum (i);
System.out.println(i);

}

}

Is the opposite, ¿why?
• 02-22-2012, 03:31 AM
Norm
Re: ¿Values by Reference? I dont understand...
Arrays are like objects. When you pass them as parameters to a method, the address of the array is passed, not a copy of the array. There is only one array and no copies, so any changes you make to the array are to the one array.
• 02-23-2012, 12:14 AM
Daxan
Re: ¿Values by Reference? I dont understand...
Thanks Norm !! :(y):

With your explication, now I understand the difference ;).
• 02-23-2012, 12:27 AM
Norm
Re: ¿Values by Reference? I dont understand...
You're welcome.