Something to Really Like in Java – VarArgs and Arrays

java-logo-thumb.png

I've been so jaded about Java that the last few years I really haven't worked to keep up with all the syntactical candy that has been added. The new for loops are a great example - as are templates: things that are in other languages that reduce typing a bit but don't really add to the power of the language.

So imagine my surprise when I started digging into varArgs in Java. First, I could see how they were used by a method:

  public void printAll(Object... things) {
    for (Object thing : things) {
      System.out.println(thing + ", ");
    }
  }

that's a pretty standard take on the C/C++ varArgs, and I'll admit, it's really nice to have. Makes the signatures of a lot of classes a lot simpler. But I needed to be able to call something with varArgs based on a stack.

For example, I have a parser that calls my code with all the arguments on a stack. I need to pop off the values - LIFO order, and then call the String.format() method with the fmt and then a bunch of Object values. But how to do that?

Thankfully, the Java guys really extended the language here. I'm really glad. They made the idea of Object... synonymous with the array: Object[]. This means that I can put all the values in an Object[] and then call the method, like this:

  /**
   * Get the format and all the args and then generate the string
   */
  public void run(Stack aStack) throws ParseException
  {
    // Check if stack is null
    if (aStack == null) {
      throw new ParseException("Stack argument null");
    }
    // see if we have a reasonable number of arguments
    if (curNumberOfParameters < 1) {
      throw new ParseException("You need at least a string format for "
            + "this call.");
    }
 
    // create an array of the proper size to hold all the args
    Object[]  varArgs = new Object[curNumberOfParameters - 1];
    if (varArgs == null) {
      throw new ParseException("I was unable to create an array to hold "
            + "the arguments. Check on it.");
    }
    // get the parameter from the stack
    for (int i = (curNumberOfParameters - 2); i >= 0; --i) {
      varArgs[i] = aStack.pop();
    }
    // finally, get the string format to use with these args
    String    fmt = (String) aStack.pop();
    // now we need to do the work... it will auto-convert the array
    aStack.push(String.format(fmt, varArgs));
  }

Needless to say, this is making the method within the parser very powerful. I now have the complete printf-like formatting available to my expressions, and while my original code worked (assuming a maximum size), this is far more flexible, and a far far better solution.

So I'm going to lighten up on Java for a while. Someone is still working on it in good ways that are just syntactic sugar.