Java Using Default Arguments

·

1 min read

In Java, you can specify default values for parameters in a method signature. This means that if a caller of the method does not provide a value for that parameter, the default value will be used. Here is an example:

public void printMessage(String message, int count = 1) {
  for (int i = 0; i < count; i++) {
    System.out.println(message);
  }
}

In this example, the printMessage method has two parameters: message, which is a string, and count, which is an integer. The count parameter has a default value of 1, so if a caller does not provide a value for it, the default value of 1 will be used.

Here is how you would call the printMessage method with the default value for count:

printMessage("Hello, world!");

This would print the message "Hello, world!" once, because the default value of 1 is used for the count parameter.

You can also specify a different value for the count parameter if you want to print the message more than once. For example:

printMessage("Hello, world!", 3);

This would print the message "Hello, world!" three times.