String are an immutable object in Java.
Therefore, concatenating Strings via the '+' operator creates a lot of Intermediate garbage Strings.
Specifically, if the Input contains N words in the sentence, then the original solution will generate 2*N intermediate Strings.
For instance, for input "Hello World from github"
The intermediate Strings are: "", "github", "github ", "github from", "github from ", github from World", "github from World ", and the result itself: "github from World Hello".
A better approach would be using the StringBuilder object which does not create intermediate Strings.
String are an immutable object in Java. Therefore, concatenating Strings via the '+' operator creates a lot of Intermediate garbage Strings. Specifically, if the Input contains N words in the sentence, then the original solution will generate 2*N intermediate Strings. For instance, for input "Hello World from github" The intermediate Strings are: "", "github", "github ", "github from", "github from ", github from World", "github from World ", and the result itself: "github from World Hello".
A better approach would be using the StringBuilder object which does not create intermediate Strings.