Here is an exercise that combines .split() and StringBuilder. Write a program that reverses the order of words in a sentence.
Given the input "Java is fun", the output should be "fun is Java". The words themselves stay intact. Only their order flips.
String sentence = "Java is fun";
String[] words = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i]);
if (i > 0) {
sb.append(" ");
}
}
System.out.println(sb.toString());
The loop starts from the last word and works backward. The if (i > 0) check prevents a trailing space after the final word. Try extending this to handle multiple spaces between words, or to reverse each individual word's characters while keeping the word order the same.