Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 7. Methods > Item 42: Use varargs judiciously - Pg. 197

ITEM 42: USE VARARGS JUDICIOUSLY 197 Item 42: Use varargs judiciously In release 1.5, varargs methods, formally known as variable arity methods [JLS, 8.4.1], were added to the language. Varargs methods accept zero or more arguments of a specified type. The varargs facility works by first creating an array whose size is the number of arguments passed at the call site, then putting the argument values into the array, and finally passing the array to the method. For example, here is a varargs method that takes a sequence of int arguments and returns their sum. As you would expect, the value of sum(1, 2, 3) is 6 , and the value of sum() is 0 : // Simple use of varargs static int sum(int... args) { int sum = 0; for (int arg : args) sum += arg; return sum; }