Can we selectively do parameters in Java?

Asked 2 years ago, Updated 2 years ago, 103 views

Can we selectively give parameters in Java? What I'm saying is that I can give you parameters, I can give you an int, I can give you a string, so that it's processed Is it possible to do that?

java optional-parameter

2022-09-22 22:34

1 Answers

Yes, it's possible There is a method of using variable arguments or method override.

private boolean defaultOptionalFlagValue = true;

//DoSomething() called when the parameter is boolean type
public void doSomething(boolean optionalFlag) {
    ...
}


//DoSomething() called when no parameter exists
public void doSomething() {
    doSomething(defaultOptionalFlagValue);
}

You create the same method for each parameter you want. I'm going to define it this way DoSomething() calls the method above if the method below is doSomething(true).

void foo(String a, Integer... b) b) {
    Integer b1 = b.length > 0 ? b[0] : 0;
    Integer b2 = b.length > 1 ? b[1] : 0;
    //...
}

foo("a");
foo("a", 1, 2);

Variable arguments write ... such as the second parameter of foo Integer...b. This means that the Integer data types can come in a fluid way from zero to several.


2022-09-22 22:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.