6

Possible Duplicate:
Does Java support default parameter values?

Is it possible to do something like this

private void function(Integer[] a, String str = "")

like in PHP. If I don't provide str, it will just be empty. In PHP it's possible, in JAVA it gives me error. Or the only solution here is to create two methods like this?

private void function(Integer[] a, String str)
private void function(Integer[] a)
Community
  • 1
  • 1
good_evening
  • 21,085
  • 65
  • 193
  • 298

5 Answers5

4

Exacly, there is no other option than:

private void function(Integer[] a, String str) {
    // ...
}

private void function(Integer[] a) {
    function(a, "");
}
hsz
  • 148,279
  • 62
  • 259
  • 315
1

Declare your method with var agrs

private void function(Integer[] a, String... s)

Remember, var args should always be the last argument of the method.

RP-
  • 5,827
  • 2
  • 27
  • 46
0

Yes, you'll have to use the second method.

private void function(Integer[] a, String str)
private void function(Integer[] a)
Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
0

That is indeed the only way to achieve such a thing, short of using a variable length method argument list.

Example:

private void function(Integer[] a, String... str) {

  for( String s : str )
  {
    System.out.println("String: " + s);
  }
}
Josh
  • 12,448
  • 10
  • 74
  • 118
0

Similar to this post:

Does Java support default parameter values?

Java does not handle this feature.

Community
  • 1
  • 1
Mik378
  • 21,881
  • 15
  • 82
  • 180