I have a string like "I am a boy"
and I want to print it so that each word appears on a separate line, like:
I
am
a
boy
What’s the right approach to achieve this using a new line in Java for each word?
I have a string like "I am a boy"
and I want to print it so that each word appears on a separate line, like:
I
am
a
boy
What’s the right approach to achieve this using a new line in Java for each word?
This is the most straightforward and readable approach:
String sentence = "I am a boy";
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
You’re breaking the sentence into parts using .split(" "), then printing each word with System.out.println(), which naturally adds a new line after each word.
If you prefer a quick one-liner and don’t mind formatting the string directly:
String sentence = "I am a boy";
System.out.println(sentence.replace(" ", "\n"));
You’re telling Java to replace every space with a newline \n
. The entire string prints in one go, with each word on a new line.