• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Java Optional method arguments/default values

jonmullen

Platinum Member
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;
}
}
 
How about:

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

Call method with: myClass(null);

I'll go try it out now...

 
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.
 
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
}
 
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.
 
Back
Top