0

Java String.join() needs atleast 3 parameters in total?

I take it the String.join() method in Java doesn't add the first parameter (the delimiter) if you only supply one more parameter (the element). Ie you need to supply more parameters (atleast 3 IN TOTAL). Ie String.join("Abc","Def") just outputs "Def" whereas String.join("Abc","Def","Ghi") outputs "DefAbcGhi" Abc is used to seperate the other parameters but if theres only one other, then there's nothing to seperate with therefore it doesn't get added. Am I correct?

22nd Aug 2024, 2:14 PM
Peter King
Peter King - avatar
2 Antworten
+ 4
In the String.join() method, the first parameter is the delimiter, and the subsequent parameters are the values to be joined. For example, if you have a function defined as join(delimiter, argA, argB), the delimiter will be used to join argA and but if you call the function with only one argument, like join(delimiter, argA), the delimiter will have no effect because there is only one value to return, so the output will simply be argA. To clarify the requirement for parameters you can think of it as needing one delimiter and at least two more values for delimiter to join them Roughly you can say it require three parameter in total to join.
22nd Aug 2024, 2:28 PM
FluffyRudy
+ 1
also List<String> abc = List.of("A","B","C"); String str = String.join(" × ", abc); System.out.println( str);
22nd Aug 2024, 5:37 PM
zemiak