Sunday, May 01, 2005

Varargs

Introduction

Varargs are methods with variable number of arguments (Schubart 2004).

Discussion

The format method takes varargs: public static String format(String pattern, Object... arguments)

import java.text.MessageFormat;

class JavaApplication {
    public static void main(String[] args) {
        String pattern = "{0} weigh {1} kg.";
        String message = MessageFormat.format(pattern, "Polar bears", new Integer(800));
        System.out.println(message);
    }
}
[user]$ javac JavaApplication.java
[user]$ java JavaApplication
Polar bears weigh 800 kg.

What happens is that the compiler write this code implicitly: String message = MessageFormat.format("{0} weigh {1} kg.", new Object[] {"Polar bears", new Integer(800)});

Conclusion

Varargs is a case of syntactic sugar. The compiler treats public static String format(String pattern, Object... arguments) like public static String format(String pattern, Object[] arguments)

References

Resources

No comments: