In Java, parameters... "There are three dots. What is this?"

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

While looking at the source, there are three dots on the parameter as shown below, what does this mean?

 public void myMethod(String... strings){
    // // method body
}

java varargs

2022-09-22 15:43

1 Answers

Yes, that's usually called varargs or variable factors. It means that String objects can come as parameters from 0 to several.

In the example above,

myMethod(); // Likely useless, but possible
myMethod("one", "two", "three");
myMethod("solo");
myMethod(new String[]{"a", "b", "c"});

You can use it in various ways like this. Importantly, variable factors don't always have to be an array, they don't have to pass them! They can have one factor value.

Also, when delivered to the method by the above formula,

public void myMethod(String... strings){
    for(String whatever : strings){
            //Access each object passed to the variable argument
    }

    // Same as above code, accessible respectively 
    for( int i = 0; i < strings.length; i++){
        // Each array is accessible in the form of strings[i].
    }
}

Also, variable factors always have to come at the end myMethod(inti, String... strings) It's possible like this, myMethod(String... strings, inti) should not come first.


2022-09-22 15:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.