Java. Variable length arguments in parameters. Overloading methods with variable length arguments. Property length. Examples




Variable length arguments in parameters. Overloading methods with variable length arguments. Property length. Examples


Contents


Search other websites:

1. What are method arguments? What are method parameters? What is the difference between arguments and parameters?

If we consider the declaration of the method, then in it after the method name indicates the list of parameters, for example

return_type SomeMethod(type1 param1, type 2 param2, ..., typeN paramN)
{
  // method body, uses param1, param2, ..., paramN parameters
  // ...
}

where

  • return_type – the type returned by the method;
  • SomeMethod – method name;
  • param1, param2, paramN – names of method parameters that are of type1, type2, typeN, respectively. The method uses these parameter names to perform its work (function).

If this method SomeMethod() is called from another code, then arguments are passed to it, for example

...
// method call, arguments are passed to the method
SomeMethod(arg1, arg2, ..., argN);
...

where arg1, arg2, argN are the arguments that are passed to the method. When called, these arguments are implicitly passed (copied) into parameters. The arg1 argument is passed (copied) to the param1 parameter, the arg2 argument is passed to param2, and the argN argument is passed to paramN.

So, parameters are variables (constants), which are described in parentheses when a method is declared. Arguments are variables, constants, values that are passed to the method when it is called from another code.

2. What are variable length arguments in methods? General form of method declaration with variable length arguments

Variable length arguments are a variable number of arguments that a method can get when called from another code (another method). In other words, a method can be called with a different number of arguments. Such a method is called a method with variable length arguments.

Methods that support a variable number of arguments must be appropriately declared. The general form of a method that receives a variable number of arguments is as follows:

return_type MethodName(type ... var) {
  // ...
  //
}

where

  • return_type – the type returned by the method;
  • MethodName – method name;
  • type – the type of variable length parameters that the method receives. The parameter list is passed as an array named var;
  • var – array name with type parameter list.

3. When is it suitable to use variable length arguments?

Using variable length arguments in methods gives the following advantages:

  • the program code is simplified, since there is no need to declare many implementations of overloaded methods that take a different number of arguments;
  • any number of any arguments of a given type can be passed to the method;
  • an arbitrary number of arguments of any type can be passed to the method. In this case, the method should take variable length arguments of type Object. Such passing does not require any additional changes in the program;
  • you do not need to first form an array of values to pass it to the method. The argument values are passed to the method, separated by commas.



4. Examples of methods that take a variable number of arguments

Example 1. The SumParams() method is declared, which calculates the sum of the variable-length arguments.

// method that takes variable length arguments
// T is an array of int arguments
static int SumParams(int ... T) {
  int sum = 0;
  for (int i=0; i<T.length; i++)
    sum += T[i];
  return sum;
}

Using the method in other program code

int sum;
sum = SumParams(1, 3, -2, 4, 8); // sum = 14
sum = SumParams(); // sum = 0
sum = SumParams(1, 2, 3); // sum = 6

Example 2. The Max() method, which finds the maximum between the argument list.

// method that finds the maximum between the parameter list
static double Max(double ... D) {
  double max;
  if (D.length == 0) return 0;

  max = D[0];
  for (int i=0; i<D.length; i++)
    if (max < D[i]) max = D[i];
  return max;
}

Using the method in another method

double max;
max = Max(3, 5, 2.8, 12.75); // max = 12.75
max = Max(4.33); // max = 4.33
max = Max(); // max = 0.0
max = Max(-1.5, -3.8, -112.23); // max = -1.5

Example 3. A method that returns an array of sorted float parameters. Parameters are sorted in descending order.

static float[] ToSortArrayFloat(float ... F) {
  float t; // additional variable
  if (F.length<2) return F;

  // insertion sort
  for (int i=0; i<F.length-1; i++)
    for (int j=i; j>=0; j--)
      if (F[j]<F[j+1])
      {
        t = F[j];
        F[j] = F[j+1];
        F[j+1] = t;
      }
  return F;
}

Method use

float[] FR; // resulting array
FR = ToSortArrayFloat(-0.5f, 0.2f, 0.3f, -0.4f); // FR = [0.3, 0.2, -0.4, -0.5]
FR = ToSortArrayFloat(1, -2, 3); // FR = [ 3.0, 1.0, -2.0 ]
FR = ToSortArrayFloat(); // FR = [ ]

5. How does the method determine the number of variable-length arguments passed to it?

When passing variable-length arguments to a method, their number is determined using the length property.

For example. Let the Average() method be set

// method that calculates the arithmetic mean of the parameter list
static double Average(double ... list) {
  double avg=0;
  int n;

  // length property - the total number of parameters passed to the method
  n = list.length;

  // calculating the sum of the items
  for (int i=0; i<n; i++)
    avg+=list[i];
  return avg/n;
}

In the method string

n = list.length;

the total number of variable-length arguments that were passed to the method is calculated.

Using a method in another program code can be, for example, the following:

double Avg;
Avg = Average(3, 5, 7, 10); // Avg = 6.25

6. Is it possible to combine ordinary arguments (parameters) with variable length arguments in a method declaration?

Yes, it is. But, provided that the following rules are followed:

  • declaration of arguments (parameters) of variable length may follow after the declaration of ordinary arguments;
  • variable length arguments must be specified in the method only once;
  • mixed ordering of ordinary arguments with variable length arguments is not allowed.






7. An example of declaring and using a method that combines ordinary arguments with variable length arguments

A declaration of a method that receives a sequence of variable-length arguments and returns a two-dimensional array formed from these arguments. The dimension of the resulting m×n array is given by ordinary arguments. The implementation of the ConvertToArray2() method is as follows

// method that converts a one-dimensional array of parameters
// to a two-dimensional array of a given size m * n
static int[][] ConvertToArray2(int m, int n, int ... params) {
  int[][] A = new int[m][n]; // resulting array
  int row, col;

  // set the value to 0 in array cells
  for (int i=0; i<m; i++)
    for (int j=0; j<n; j++)
      A[i][j]=0;

  int len = params.length;
  if (len>m*n) len=m*n;

  // form the array A
  for (int i=0; i<len; i++)
  {
    row = i/n;
    col = i-row*n;
    A[row][col]=params[i];
  }

  // returning array from method
  return A;
}

Using an array in other program code

// testing the ConvertToArray2() method
int[][] res; // resulting array
int m=2, n=3; // array dimension

// the sequence is converted into a two-dimensional array of size 2 * 3
// extra items are truncated
resA = ConvertToArray2(m,n,11,12,13,21,22,23,24,25,26);

// resA = { { 11, 12, 13}, { 21, 22, 23} }
// output of array res
for (int i=0; i<m; i++)
{
  for (int j=0; j<n; j++)
    System.out.print(" " + resA[i][j]);
  System.out.println();
}

As a result of executing the above code snippet, the following result will be displayed:

11 12 13
21 22 23

8. An example of declaring and using a method with a variable number of arguments that are instances of a class

The class Book is given that implements the book.

// class implementing a book
class Book {
  String title; // title of book
  String author; // authors name
  int year; // the year of publishing
  float price; // cost of book
}

Below is the GetMaxCostBook() method, which receives a variable number of arguments of type Book. The method returns a reference to the book that has the highest value.

// method that gets an array of books as parameters
// the method that returns the book that has maximum cost
static Book GetMaxCostBook(Book ... B) {
  Book bk=null;

  // checking
  if (B.length==0)
    return bk;

  // the computation cycle of the maximum cost book
  bk = B[0];
  for (int i=1; i<B.length; i++)
    if (bk.price<B[i].price)
      bk = B[i];
  return bk;
}

A demonstration of using the GetMaxCostBook() method can be as follows:

// Testing GetMaxCostBook() method
Book B1 = new Book();
Book B2 = new Book();
Book B3 = new Book();
Book B4 = new Book();

// books formation
B1.title = "Title1";
B1.author = "Author1";
B1.price = 12.50f;
B1.year = 2007;

B2.title = "Title2";
B2.author = "Author2";
B2.price = 7.77f;
B2.year = 2023;

B3.title = "Title3";
B3.author = "Author3";
B3.price = 19.95f;
B3.year = 2019;

B4.title = "Title4";
B4.author = "Author4";
B4.price = 11.15f;
B4.year = 2009;

// method call
Book resBook;

resBook = GetMaxCostBook(B1,B2,B3,B4);
if (resBook!=null)
{
  // output the result
  String title = resBook.title;
  String author = resBook.author;
  float price = resBook.price;
  int year = resBook.year;
  System.out.println("title = " + title);
  System.out.println("author = " + author);
  System.out.println("price = " + price);
  System.out.println("year = " + year);
}

As a result of executing the above code, the following result will be displayed.

title = Title3
author = Author3
price = 19.95
year = 2019

9. How is implemented the methods overloading with variable length arguments? Example

A method that accepts variable-length arguments may have several overloaded implementations. Such implementations differ in the type of values they receive.

Example. A CalcSum class is declared, containing three overloaded implementations of the Sum() method, which calculates the sum of parameters for the types int, double, and float.

// class that contains an overloaded Sum() method
class CalcSum {
  // overloaded method Sum() for integer types
  int Sum(int ... params) {
    int sum = 0;
    for (int i=0; i<params.length; i++)
      sum+=params[i];
    return sum;
  }

  // Sum() for double type
  double Sum(double ... params) {
    double sum = 0;
    for (int i=0; i<params.length; i++)
      sum+=params[i];
    return sum;
  }

  // Sum() for float type
  float Sum(float ... params) {
    float sum = 0.0f;
    for (int i=0; i<params.length; i++)
      sum+=params[i];
    return sum;
  }
}

public class VarArguments {
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    CalcSum cs = new CalcSum();
    int sumInt;
    double sumDouble;
    float sumFloat;

    // calling an overloaded method of type int
    sumInt = cs.Sum(2,3,5);

    // calling an overloaded method of type double
    sumDouble = cs.Sum(2.05, 1.88, -3.95, 4.4);

    // calling an overloaded method of type float
    sumFloat = cs.Sum(0.8f, -0.3f, 2.5f, 2.34f);

    System.out.println("sumInt = " + sumInt);
    System.out.println("sumDouble = " + sumDouble);
    System.out.println("sumFloat = " + sumFloat);
  }
}

As a result of executing the main() function, the following result will be displayed.

sumInt = 10
sumDouble = 4.38
sumFloat = 5.34

10. What is the essence of the “ambiguity” error when using variable length arguments?

An ambiguity error may occur if two or more of the implementation of the overloaded method are suitable for a call. In this case, the compiler does not know which of the overloaded methods to call.

For example. Let overloaded methods named Method() be given

static void Method(int ... params) {
  // ...
}

static void Method(boolean ... params) {
  // ...
}

then when you invoke

Method(); // ambiguity error

the compiler will not know which overloaded version of Method() to call. This concerns the combination of existing simple types with the type boolean. If you declare two overloaded methods with types int and double, then this error will not occur.

11. How to make the method accept any number of arguments of any type? Example

In this case, a method with variable-length arguments of type Object is declared. As you know, in Java, all classes are derived from the common root class Object. Sometimes such methods are effective, especially if the type (class) that receives the method is unknown.

For example. The Error class and the ShowInfo() method, which accepts variable length arguments of type Object, are declared. The program code of the module, which demonstrates the use of the method, which takes any number of any arguments is as follows

// class that implements some possible error in some program
class Error {
  String errorString; // error message
  int code; // error code

  Error(String _errorString, int _code) {
    errorString = _errorString;
    code = _code;
  }
}

public class VarArguments {
  // method that accepts variable length arguments of type Object
  static void ShowInfo(Object ... objects) {
    String s;

    // the output information about the arguments passed to the method
    for (Object o : objects)
      System.out.println(o.toString()+" ");
    System.out.println("----------------");
  }

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    // Demonstration the use of the ShowInfo() method
    // 1. Passing arguments of type int
    ShowInfo(3,5,7,2);

    // 2. Passing arguments of type Error
    Error e1 = new Error("Divide by 0", 1);
    Error e2 = new Error("Abnormal program termination", 2);
    ShowInfo(e1,e2, new Object[] { new Error("Error message", 3) });

    // 3. Passing arguments of type float
    ShowInfo(2.8, 3.55, -10.12, 18.13, 0.01);
  }
}

As a result of executing the main() function, the following result will be displayed.

3
5
7
2
----------------
Error@1db9742
Error@106d69c
[Ljava.lang.Object;@52e922
----------------
2.8
3.55
-10.12
18.13
0.01


Related topics