161

I have a string like

"I am a boy".

I would like to print it this way

"I 
am 
a
boy".

Can anybody help me?

0

18 Answers 18

160
System.out.println("I\nam\na\nboy");

System.out.println("I am a boy".replaceAll("\\s+","\n"));

System.out.println("I am a boy".replaceAll("\\s+",System.getProperty("line.separator"))); // portable way
Sign up to request clarification or add additional context in comments.

2 Comments

@the_prole explained here
The third option is best for portability.
154

You can also use System.lineSeparator():

String x = "Hello," + System.lineSeparator() + "there";

2 Comments

In the older Java versions: System.getProperty("line.separator").
Shortcut: String x = "Hello, %n there"; . Added spaces around %n just for the sake of readability.
63

Example

System.out.printf("I %n am %n a %n boy");

Output

I 
 am 
 a 
 boy

Explanation

It's better to use %n as an OS independent new-line character instead of \n and it's easier than using System.lineSeparator()

Why to use %n, because on each OS, new line refers to a different set of character(s);

Unix and modern Mac's   :   LF     (\n)
Windows                 :   CR LF  (\r\n)
Older Macintosh Systems :   CR     (\r)

LF is the acronym of Line Feed and CR is the acronym of Carriage Return. The escape characters are written inside the parenthesis. So on each OS, new line stands for something specific to the system. %n is OS agnostic, it is portable. It stands for \n on Unix systems or \r\n on Windows systems and so on. Thus, Do not use \n, instead use %n.

1 Comment

29

It can be done several ways. I am mentioning 2 simple ways.

  1. Very simple way as below:

    System.out.println("I\nam\na\nboy");
    
  2. It can also be done with concatenation as below:

    System.out.println("I" + '\n' + "am" + '\n' + "a" + '\n' + "boy");
    

Comments

16

Try:

System.out.println("I\nam\na\nboy");

Comments

13

To make the code portable to any system, I would use:

public static String newline = System.getProperty("line.separator");

This is important because different OSs use different notations for newline: Windows uses "\r\n", Classic Mac uses "\r", and Mac and Linux both use "\n".

Commentors - please correct me if I'm wrong on this...

Comments

8

\n is used for making separate line;

Example:

System.out.print("I" +'\n'+ "am" +'\n'+ "a" +'\n'+ "boy"); 

Result:

I
am
a
boy

1 Comment

Please read other answers first. Your solution is already there.
7

Platform-Independent Line Breaks:

finalString = "physical" + System.lineSeparator() + "distancing";
System.out.println(finalString);

Output:

physical
distancing

Notes:

  • Java 6: System.getProperty("line.separator")
  • Java 7 & above: System.lineSeparator()

Comments

6

What about %n using a formatter like String.format()?:

String s = String.format("I%nam%na%nboy");

As this answer says, its available from java 1.5 and is another way to System.getProperty("line.separator") or System.lineSeparator() and, like this two, is OS independent.

Comments

6

If you simply want to print a newline in the console you can use \n for newlines.

If you want to break text in Swing components you can use HTML and its <br>:

String str = "<html>first line<br>second line</html>";

1 Comment

This works for me. And I am using unicode font. This works better.
5

If you want to have your code os-unspecific you should use println for each word

System.out.println("I");
System.out.println("am");
System.out.println("a");
System.out.println("boy");

because Windows uses "\r\n" as newline and unixoid systems use just "\n"

println always uses the correct one

3 Comments

This is not a good solution to write too many System.out.println()
@op Remember that println() adds a newline character at the end of the string (not the beginning).
@Hachi, System.lineSeparator() or System.getProperty("line.separator") can used to make code system independent.
1

Full program example, with a fun twist:

Open a new blank document and save it as %yourJavaDirectory%/iAmABoy/iAmABoy.java. "iAmABoy" is the class name.

Paste the following code in and read through it. Remember, I'm a beginner, so I appreciate all feedback!

//The class name should be the same as your Java-file and directory name.
class iAmABoy {

    //Create a variable number of String-type arguments, "strs"; this is a useful line of code worth memorizing.
    public static void nlSeparated(String... strs) {

        //Each argument is an str that is printed.
        for (String str : strs) {

            System.out.println(str);

        }

    }

    public static void main(String[] args) {

        //This loop uses 'args' .  'Args' can be accessed at runtime.  The method declaration (above) uses 'str', but the method instances (as seen below) can take variables of any name in the place of 'str'.
        for (String arg : args) {

            nlSeparated(arg);

        }

        //This is a signature.  ^^
        System.out.print("\nThanks, Wolfpack08!");
    } 

}

Now, in terminal/cmd, browse to %yourJavaDirectory%/iAmABoy and type:

javac iAmABoy.java
java iAmABoy I am a boy

You can replace the args I am a boy with anything!

2 Comments

You do not need two loops. Either pass args directly to nlSeparated() or make nlSeparated() take a scalar String instead of an array. First option is probably better. Also, print your signature with println instead of print.
In main, replace for (String arg : args) { nlSeparated(arg); } with just nlSeparated(args);. nlSeparated already accepts a list of Strings. For a better explanation, see here: stackoverflow.com/a/12534579/2988730
1

Go for a split.

String string = "I am a boy";
for (String part : string.split(" ")) {
    System.out.println(part);
}

Comments

0

I use this code String result = args[0].replace("\\n", "\n");

public class HelloWorld {

    public static void main(String[] args) {
        String result = args[0].replace("\\n", "\n");
        System.out.println(result);
    }
}

with terminal I can use arg I\\nam\\na\\boy to make System.out.println print out

I
am
a
boy

enter image description here

Comments

0

Here it is!! NewLine is known as CRLF(Carriage Return and Line Feed).

  • For Linux and Mac, we can use "\n".
  • For Windows, we can use "\r\n".

Sample:

System.out.println("I\r\nam\r\na\r\nboy");

Result:
output

It worked for me.

Comments

0

With Java 21, you can use text blocks. See the example below:

String mapping = analysis.getMappingItems().stream()
  .map(mappingItem -> String.format("""
    <item>
      <name>%s</name>
      <mermaid-line>%d</mermaid-line>
    </item>""".indent(4), mappingItem.statusName(), mappingItem.edgeNumber()))
  .collect(Collectors.joining(""))
  .stripTrailing();

You see here that the string literal is indented to look nice within the .java file. The Java compiler removes this incidental whitespace and keeps the essential whitespace. Then the .indent(4)method call adds four trailing spaces, essential indentation I want to add.

I understood from the documentation that no trailing newline would be added because the """ does not appear on a newline. From my output I concluded that a trailing newline was added. This is why the .joining()method call takes an empty string.

See https://docs.oracle.com/en/java/javase/21/text-blocks/index.html.

Comments

-1

you can use <br> tag in your string for show in html pages

2 Comments

It's always a bad idea to embed markup in your output. You never know what display technology your users are using. Best to keep it as generic as possible, and use a formatting filter for display if needed.
I said it just works in html page, it's just a suggest for who want to show a simple text in web pages.
-1

Here I am using the split function. I braked String from spaces. then I used println function and printed the value.

    public class HelloWorld{

     public static void main(String []args){
              String input = "I am a boy";
              String[] opuput = input.split(" ");
          for (int i = 0; i < opuput.length; i++)
                System.out.println(opuput[i]);
         }        
}

1 Comment

input is not defined. That's not an issue when you're just providing some exemplary code, but this code block gives the impression of being a full runnable example (since it has a public static void main, however it doesn't compile. So either make it a short 3-line sample that references "invisible" variables or make it an actually runnable sample, this mixture is just confusing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.