# Thread: returning an array weird problem

1. Member
Join Date
Jan 2011
Posts
3
Rep Power
0

## returning an array weird problem

Here's an example of the code i'm having a problem with

Java Code:
```
public static double[] convertT(double[] t){
double[] tArray=t;
int index=0;

for (double num:t){
tArray[index]=num+273.1;
index++;
}

return tArray;
}

public static void main(String[] args) {

double[] tempC = {77.0, 77.0, 63.5, 53.3, 53.3, 77.6, 77.6, 77.6, 52.9, 52.9, 77.6,
62.7, 53.7, 53.7, 79.5, 79.5, 64.0, 64.0, 54.5, 39.2, 38.3, 49.4,
40.2, 40.2, 40.2, 40.2, 39.7, 40.2, 40.2, 40.2, 39.9, 39.9, 39.8};

double[] tempK=convertT(tempC);

for (double num:tempK){
System.out.print(num+":");
}

}```
Okay better Description. I have an array of temperatures in degrees C and need to convert them into degrees K. I pass the array into the converT function and change each value inside an temp array. I have checked the temp array before returning it and the result is correct. I then return the array and assign it to the new array tempK in the main line. The values that are in tempK do not agree with the values that were in the temp array before i returned it.

Any ideas?
Last edited by mcleanj; 01-28-2011 at 06:26 AM. Reason: formatting plus description

3. When you pass Object (and arrays are Objects) you pass a reference to the Object/array and not a copy of it. So in your code the variables tempC, t, tArray and tempK all reference the same array. So when you make a change to one of the variables, all the other variables see that change.

Solution: create a new array in your method.

4. Member
Join Date
Jan 2011
Posts
3
Rep Power
0
hopefully thats a bit better thanks for the links new to this forum

5. Member
Join Date
Jan 2011
Posts
3
Rep Power
0
Thanks i forgot that in java arrays were objects.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•