Add newline character Java code example (\r \n \r\n)


If you want to add a line break in your output string in your Java code, you can make use of the newline character java method from the System class called System.lineSeparator(),

Example 1: Java newline using System.lineSeparator()

public class JavaNewLineCharExample {

    public static void main(String... args) {

        String myString = "Hello" + System.lineSeparator() + "World!";
        System.out.println(myString);
    }
}

Output:
Hello
World!

Example 2: Using \r character

public class JavaNewLineCharExample {

    public static void main(String... args) {

        String myString = "Hello \r World!";
        System.out.println(myString);
    }
}

Output:
Hello
 World!

Example 3: Using \n character

public class JavaNewLineCharExample {

    public static void main(String... args) {

        String myString = "Hello \r World!";
        System.out.println(myString);
    }
}

Output:
Hello
 World!

Example 4: Using \r\n character

public class JavaNewLineCharExample {

    public static void main(String... args) {

        String myString = "Hello \r\n World!";
        System.out.println(myString);
    }
}

Output:
Hello
 World!

Java newline example
Java newline example

Note: It is always better to use the example 1 approach of using System.lineSeparator() because it will use the new line character based on what platform you are using/executing the code, example 2, 3 and 4 are platform dependent.



Have Questions? Post them here!



Recent Posts:




Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and Software Developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include Learnings, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.