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!
Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap