0
Simple question
What is the output of this code? public class Program { public static void main(String[] args) { String a = “one”, b = “two”; String c = String.join(a, b); System.out.print(c); } } Answer: two - please explain me
3 Antworten
+ 5
The join method takes at first a char sequence delimeter and then another char sequence for the elements
String.join("/", "a","b","c") would be: "a/b/c"
String.join("+", "1","2","3","4") would be "1+2+3+4"
In your case: a is the delimeter and b the element. One element don't need an delimeter, so the output is just "two". You can see what happens if you add another String.
String c = String.join(a,b,"three");
For more details you can read this article: https://www.javapoint.com/java-string-join
+ 3
In this case you are passing two strings to the join() method, so the following method signature is invoked:
public static String join(CharSequence delimiter, CharSequence... elements)
a is the delimiter
b is the first element
But because there are no more elements to combine, the delimiter is not used. That's why the result is two.
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence...-
+ 2
For join method, the first argument is delimiter..., next arguments are string to be joined..
For ex:
S=String.join("@", "abc", "cdf"," ef");
Now S=abc@cdf@ef;
Delimiter is added in between string not at end, not at start so,
Since in your example, have only one string, one delimiter, output is two..