Arrays, Variables, [ and {
Variable initialization, assignments and use in array construction can be tricky to varying degrees in different programming languages.
When a variable is used during initialization of an array, some may assume that assignment to that variable will be carried to the array, too.
In this short note I want to give a couple of examples to note the difference between "{ }" and "[ ]" which are used when it comes to array assignments and initialization in Java. In fact, "{" and "[" distinctively mark assignment during innitialization or later.
I'm just going to give the code fragments and leave it there. I give two examples. One from Java and one from Ruby. My purpose here is not to be correct style-wise but simply to make a point that you probably already know but might forget once in a while. Try to run them on your own, fix any bugs and see what the difference is.
Here is the Java fragment:
public class TestVariableMeaningInArrays{
public static void main(String args[ ])
{
String[ ] x={"Iran", "US"}, y={"Tehran", "Washington DC"};
String[ ][ ] z={x,y};
print2By2(z);
y[0]="Isfahan";
y[1]="Chicago";
print2By2(z);
y=new String[ ]{"Shiraz", "Santa Barbara"};
print2By2(z);
}
private static void print2By2(String[ ][ ] z){
System.out.println(z[0][0]);
System.out.println(z[0][1]);
System.out.println(z[1][0]);
System.out.println(z[1][1]);
}
}
And, here, is the rough Ruby equivalent:
x=["Iran", "US"] y=["Tehran", "Washington DC"] z=[x,y] puts z y[0]="Isfahan" y[1]="Chicago" puts z y=["Shiraz", "Santa Barbara"] puts z
So, what's the point? Not much, really.
Ruby seems a little vaguer here because it does not sharply (in a marked way) distinguish between "new"-ing and element assignments. It is partly because in both cases, we have "[ ]". Please don't get me wrong. I don't want to criticize Ruby here. For a discerning programmer, it should be obvious that there's a difference between the assignments occuring on lines 5 and 6 and that occuring on line 8 of the Ruby program above.
- Login or register to post comments
- Printer-friendly version
- mortazavi's blog
- 394 reads





