Skip to main content

Java - Varargs



Welcome to Java and varargs (short for variable arguments). In a situation where it is needed to pass in an variable amount of arguments to a method, varargs is a good answer.
Some portions of this article are the same as this one: C# params. This is because they are both written by me and cover very similair topics. The code in both examples has the same idea. This is done to create a consistency for both articles. With that in mind lets continue.
Before we get to the code there are a couple things to keep in mind.
  1. The varargs parameter needs to be the last in line;
  2. Only one vararg parameter is allowed.
 The basic syntax is as follows:
?
1
public void methodName(parameterType... parameterName){}
Notice the three dots behind parameterType. This is to tell the compiler that you want to use variable arguments. So what does the compiler in the background? It gathers all of the values and puts them into an array. The type of params can be anything. You can change it to string, bool, Object, user defined object and more. To read the values just use the normal array methods.
In the example code i created two methods. One for printing int values and the other for printing string values. Perhaps not a realistic example but i wanted to keep this short and simple. Also note that i pass in both an array of strings and one or more strings separated by a comma.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class test {
 
    public static void main(String[] args) {
         
        printString("One var input");
         
        String[] array = new String[3];
        array[0] = "array input #1";
        array[1] = "array input #2";
        array[2] = "array input #3";
         
        printString(array);
        printString("Two var input #1", "Two var input #2");
         
        printIntegers(1);
        printIntegers(2,3,4);
        printIntegers(633,7474,74345,52432);
    }
     
    public static void printIntegers(int...params)
    {
        String temp = "";
         
        for(int s : params)
        {
            temp += s + " | ";
        }
         
        System.out.println(temp);
    }
     
    public static void printString(String... params)
    {
        String temp = "";
         
        for(String s : params)
        {
            temp += s + " | ";
        }
         
        System.out.println(temp);
    }
}
The output is as follows:

Comments

Popular posts from this blog

How To Install Age Of Empires 2: Forgotten Empires

There is a new unofficial expansion pack for Age of Empires 2 called Forgotten Empires. To install Forgotten Empires you need the original Age of Empires II "Age of Kings" and the official expansion pack "The Conquerors". When Age of Empires 2 came out I could play this game non stop for hours and with this new expansion pack it looks like that's still possible even though I'm not really much of a gamer ;). Features 5  brand new civilizations 30  new technologies 9  new units 1000  population limit 11  new maps 1  new building 2  new architecture sets 20  new scenario editor objects ?  new campaigns Full  unlimited  resolutions (Widescreen included) Install Make sure to have Age of Empires II: The Conquerors installed Download the installer exe | zip Unzip the file into your Age of Empires II Installation folder (typically C:\Program Files\Microsoft Games\Age of Empires II\) Select your ...

Block Spotify Ads

Spotify is a digital music service that gives you access to millions of songs without having to pay a penny.  Off couse you can pay so you don't have to listen to those ads anymore, but there is a free way to block Spotify ads. The best ad blocker at the moment is Blockify that mutes Spotify whenever it detects an audio ad. When the ad finished playing it will unmute Spotify and play your tracks. Blockify also adds customizable hotkeys to Spotify, so you can skip tracks, play, pause, shuffle, and change the volume with keyboard shortcuts. Features: Mutes Spotify whenever it detects an audio ad. Play your own MP3s during adverts. Control Spotify via keyboard hotkeys. Easy to use, totally portable. Unlike every other advert blocker, it doesn't rely on a list! Download Blockify

Java - Calculate Factorial

This code snippet calculates the factorial of a number up to 20. Because of the large numbers it can't go higher then 20, 21 factorial is: 51.090.942.171.709.440.000. There are two methods in this code, one for calculating it with recursion and one non-recursive. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class Factorial {      public static void main(String[] args) {          System.out.println(factorialRecursion( 20 ));          System.out.println(factorial( 20 ));      }      public static long factorialRecursion( long l) {          if (l < 2 )              return 1 ;          else ...