Does Java allow Default Arguments?

Views 725

Answer:

No, Java does not support default arguments in the same way some other programming languages do, like Python or C++. In Java, every parameter of a method must be explicitly specified in the method signature, and when you call a method, you must provide values for all parameters.

If you want to simulate default values, you can achieve this by overloading methods. Overloading is the ability to define multiple methods with the same name but with different parameter lists. Each overloaded method can then provide default values for some parameters.

Here's an example:


public class Example {
    // Method with two parameters
    public void myMethod(int a, int b) {
        System.out.println("a: " + a + ", b: " + b);
    }

    // Overloaded method with one parameter, providing a default value for the second parameter
    public void myMethod(int a) {
        // Assuming a default value for the second parameter, e.g., 0
        myMethod(a, 0);
    }

    public static void main(String[] args) {
        Example example = new Example();
        
        // Call the first method
        example.myMethod(10, 20);

        // Call the second method, providing only one argument
        example.myMethod(5);
    }
}

In this example, if you call myMethod with one argument, it will use the default value for the second parameter. If you call it with two arguments, it will use both values.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.