Java Optional method arguments/default values

jonmullen

Platinum Member
Jun 17, 2002
2,517
0
0
How do I define and argument in a method as optional, that way if it is not supplied it is ok. In php it would be something like this

function($required,$optional="option")
{
print $required;
if($optional != "option")
{
print $optional;
}
}
 

Mitzi

Diamond Member
Aug 22, 2001
3,775
1
76
How about:

Class myClass(paramType paramName) {
if (paramName == null) { blah }
...
}

Call method with: myClass(null);

I'll go try it out now...

 

Mitzi

Diamond Member
Aug 22, 2001
3,775
1
76
public class test {

public static void main(String[] args) {
// String myString = "hello";
String myString = null;
myMethod(myString);
}

static void myMethod (String myParam) {
if (myParam == null) { myParam = "default"; }
System.out.println("myParam: " + myParam);
}
}


Try that. Note that you still need to pass a parameter to the method but it is acceptable to simply pass null (i.e. myMethod(null);).

There may be a way to specifically identify that a parameter is optional but I'm not aware of it, sorry.
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
The nice way to do it is to have two methods:

static void myMethod() {
//just calls the other version of the method, with null values
myMethod(null);
}

static void myMethod(String test) {
//actually does stuff
}
 

AmigaMan

Diamond Member
Oct 12, 1999
3,644
1
0
Originally posted by: Kilrsat
The nice way to do it is to have two methods:

static void myMethod() {
//just calls the other version of the method, with null values
myMethod(null);
}

static void myMethod(String test) {
//actually does stuff
}

what he/she said.