[java] how to set default method argument values?

Is it possible to set the default method parameter values in Java?

Example: If there is a method

public int doSomething(int arg1, int arg2)
{
//some logic here
    return 0;
}

is it possible to modify the given method in order to be able to call it with and without parameters?

example:

doSomething(param1, param2);
doSomething();

Thanks!

This question is related to java parameters methods default-value

The answer is


Hopefully I am not misunderstanding this document, but if your using Java 1.8, in theory, you could accomplish something like this by defining a working implementation of a default method ("defender methods") within an interface that you implement.

interface DoInterface {
    void doNothing();
    public default void remove() {
       throw new UnsupportedOperationException("remove");
    }
    public default int doSomething( int arg1, int arg2) {
        val = arg1 + arg2 * arg1;
        log( "Value is: " + val );
        return val;
    }
}
class DoIt extends DoInterface {
    DoIt() {
        log("Called DoIt constructor.");
    }
    public int doSomething() {
        int val = doSomething( 0, 100 );
        return val;
    }
}

Then, call it either way:

DoIt d = new DoIt();
d.doSomething();
d.soSomething( 5, 45 );

You can't declare default values for the parameters like C# (I believe) lets you, but you could simply just create an overload.

public int doSomething(int arg1, int arg2) {
    //some logic here
    return 0;
}

//overload supplies default values of 1 and 2
public int doSomething() {
    return doSomething(1, 2);
}

If you are going to do something like this please do everyone else who works with your code a favor and make sure you mention in Javadoc comments what the default values you are using are!


You can accomplish this via method overloading.

public int doSomething(int arg1, int arg2)
{
        return 0;
}

public int doSomething()
{
        return doSomething(defaultValue0, defaultValue1);
}

By creating this parameterless method you are allowing the user to call the parameterfull method with the default arguments you supply within the implementation of the parameterless method. This is known as overloading the method.


No. Java doesn't support default parameters like C++. You need to define a different method:

public int doSomething()
{
   return doSomething(value1, value2);
}

It's not possible to default values in Java. My preferred way to deal with this is to overload the method so you might have something like:

public class MyClass
{
  public int doSomething(int arg1, int arg2)
  {
    ...
  }

  public int doSomething()
  {
    return doSomething(<default value>, <default value>);
  }
}

You can overload the method with different parameters:

public int doSomething(int arg1, int arg2)
{
//some logic here
        return 0;
}

public int doSomething(
{
doSomething(0,0)
}

If your arguments are the same type you could use varargs:

public int something(int... args) {
    int a = 0;
    int b = 0;
    if (args.length > 0) {
      a = args[0];
    }
    if (args.length > 1) {
      b = args[1];
    }
    return a + b
}

but this way you lose the semantics of the individual arguments, or

have a method overloaded which relays the call to the parametered version

public int something() {
  return something(1, 2);
}

or if the method is part of some kind of initialization procedure, you could use the builder pattern instead:

class FoodBuilder {
   int saltAmount;
   int meatAmount;
   FoodBuilder setSaltAmount(int saltAmount) {
       this.saltAmount = saltAmount;
       return this;
   }
   FoodBuilder setMeatAmount(int meatAmount) {
       this.meatAmount = meatAmount;
       return this;
   }
   Food build() {
       return new Food(saltAmount, meatAmount);
   }
}

Food f = new FoodBuilder().setSaltAmount(10).build();
Food f2 = new FoodBuilder().setSaltAmount(10).setMeatAmount(5).build();

Then work with the Food object

int doSomething(Food f) {
    return f.getSaltAmount() + f.getMeatAmount();
}

The builder pattern allows you to add/remove parameters later on and you don't need to create new overloaded methods for them.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to parameters

Stored procedure with default parameters AngularJS ui router passing data between states without URL C#: HttpClient with POST parameters HTTP Request in Swift with POST method In Swift how to call method with parameters on GCD main thread? How to pass parameters to maven build using pom.xml? Default Values to Stored Procedure in Oracle How do you run a .exe with parameters using vba's shell()? How to set table name in dynamic SQL query? How to pass parameters or arguments into a gradle task

Examples related to methods

String method cannot be found in a main class method Calling another method java GUI ReactJS - Call One Component Method From Another Component multiple conditions for JavaScript .includes() method java, get set methods includes() not working in all browsers Python safe method to get value of nested dictionary Calling one method from another within same class in Python TypeError: method() takes 1 positional argument but 2 were given Android ListView with onClick items

Examples related to default-value

How to set a default value in react-select How to set default values in Go structs What is the default value for Guid? CURRENT_DATE/CURDATE() not working as default DATE value Entity Framework 6 Code first Default value Default values and initialization in Java Python argparse: default value or specified value Javascript Get Element by Id and set the value Why is the default value of the string type null instead of an empty string? SQL Column definition : default value and not null redundant?