Skip to main content

Arrays, Variables, [ and {

Posted by mortazavi on September 11, 2006 at 1:48 PM PDT

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};
    y=new String[ ]{"Shiraz", "Santa Barbara"};
  private static void print2By2(String[ ][ ] z){

And, here, is the rough Ruby equivalent:

  x=["Iran", "US"]
  y=["Tehran", "Washington DC"]
  puts z
  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.

Related Topics >>