From the course: Advanced Java Programming
Unlock the full course today
Join today to access over 22,500 courses taught by industry experts or purchase this course individually.
Using varargs in Java - Java Tutorial
From the course: Advanced Java Programming
Using varargs in Java
- [Instructor] Sometimes you might want to write a method that takes a variable number of arguments. In Java there is a feature called variable-length arguments, or varargs for short, which allows you to do this. In this example, I have a method called printShoppingList. That prints a heading, and then the two string items that are passed in as arguments. But because I might have three items, I have also overridden this method with another version that takes three arguments. However, I might have any number of items that I want to add to the shopping list. Using this approach, I would have to keep overriding the method for each time I wanted to use it with a different number of items. The method would also get very long if there were lots of items. So I have another overridden version of the method that takes an array of items and prints each item in the array. In the main method, I have created a number of items which I print as a list using the version that takes three parameters. I…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.