0

I want to write a function in java which has default parameters, but if I pass value to those parameters then it should take those values in place of those default parameters. I know how to write the function in Python. But I want to implement the exact same function(or method) in Java.

This is the sample python code

    def myFunc(name, std = 3, rollNo = 61, branch = "CSE"):
        print("My name is %s, I read in class %d, my roll no is %d, my branch is %s" %(name, 
                    std, rollNo, branch))

    myFunc("hacker", 3)
    myFunc("hacker", 3, 60)
    myFunc("hacker")

This the output of the python code

    My name is hacker, I read in class 3, my roll no is 61, my branch is CSE
    My name is hacker, I read in class 3, my roll no is 60, my branch is CSE
    My name is hacker, I read in class 3, my roll no is 61, my branch is CSE

I want to write a function in Java that does the exact same thing.

Akash Nath
  • 63
  • 4
  • 1
    Java doesn't support default parameters. You have to write a method with all parameters and then write additional methods with less parameters which call the first method with the additional default values. – Michael Butscher Sep 02 '21 at 17:50

1 Answers1

1

The Java way to have default parameters is with Method Overloading. This should be the solution you're looking for:

public static void myFunc(String name) {
   myFunc(name, 3, 61, "CSE");
}

public static void myFunc(String name, int std) {
   myFunc(name, std, 61, "CSE");
}

public static void myFunc(String name, int std, int rollNo) {
   myFunc(name, std, rollNo, "CSE");
}

public static void myFunc(String name, int std, int rollNo, String branch) {
        System.out.println(String.format("My name is %s, I read in class %d, my roll no is %d, my branch is %s", name, std, rollNo, branch));
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
zakpruitt
  • 162
  • 2
  • 11
  • You're not wrong. But although Java doesn't have "default parameters" (like C++, C# ... or Python), there are actually *SEVERAL* different ways to achieve the same results. Operator overloading is one way. [varargs](https://www.baeldung.com/java-varargs) is another. Look [here](https://stackoverflow.com/a/19719701/421195), [here](https://www.delftstack.com/howto/java/does-java-support-default-parameters-value/) or [here](https://stackify.com/optional-parameters-java/) – paulsm4 Sep 02 '21 at 18:32