Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java support default parameter values?

I came across some Java code that had the following structure:

public MyParameterizedFunction(String param1, int param2) {     this(param1, param2, false); }  public MyParameterizedFunction(String param1, int param2, boolean param3) {     //use all three parameters here } 

I know that in C++ I can assign a parameter a default value. For example:

void MyParameterizedFunction(String param1, int param2, bool param3=false); 

Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?

like image 976
gnavi Avatar asked Jun 15 '09 18:06

gnavi


People also ask

Does Java have default parameters?

Short answer: No. Fortunately, you can simulate them. Many programming languages like C++ or modern JavaScript have a simple option to call a function without providing values for its arguments.

Can parameters have default values?

In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .

How do I set default value in Java?

Remember, to get the default values, you do not need to assign values to the variable. static boolean val1; static double val2; static float val3; static int val4; static long val5; static String val6; Now to display the default values, you need to just print the variables.


1 Answers

No, the structure you found is how Java handles it (that is, with overloading instead of default parameters).

For constructors, See Effective Java: Programming Language Guide's Item 1 tip (Consider static factory methods instead of constructors) if the overloading is getting complicated. For other methods, renaming some cases or using a parameter object can help. This is when you have enough complexity that differentiating is difficult. A definite case is where you have to differentiate using the order of parameters, not just number and type.

like image 170
Kathy Van Stone Avatar answered Sep 17 '22 14:09

Kathy Van Stone