[java] Java String new line

I have string like

"I am a boy".

I want to print like this way

"I 
am 
a
boy".

Can anybody help me?

This question is related to java string newline

The answer is


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

This works It will give one space character also along before enter character


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


You can also use System.lineSeparator():

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

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


Try:

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

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


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...


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.


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!


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");
    

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

Go for a split.

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

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()

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.


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:

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

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.


\n is used for making separate line;

Example:

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

Result:

I
am
boy

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to newline

How can I insert a line break into a <Text> component in React Native? Print "\n" or newline characters as part of the output on terminal Using tr to replace newline with space How to write one new line in Bitbucket markdown? Line break in SSRS expression How to insert a new line in Linux shell script? Replace CRLF using powershell How to write new line character to a file in Java What is the newline character in the C language: \r or \n? How to print values separated by spaces instead of new lines in Python 2.7