Search code examples
javacarriage-return

Java carriage return \r doesn't seem to work correctly


Here's my java code:

// file name is Strings.java
public class Main {
    public static void main(String[] args){
        String txt = "Hello\rWorld!";
        System.out.println(txt);

        String txt2 = "Trying\rthis";
        System.out.println(txt2);
    } 
}

And I tried to execute it from my terminal, and saw this:

$ java Strings.java 
World!
thisng

I have also tried to execute this from Visual Studio Code, same results. So the outputs are different than what is written in this tutorial. Could someone please tell me why? Thank you!


Solution

  • This depends on the operation system: Linux (\n), Mac (\r), Windows (\r\n). All have different new line symbols. See Adding a Newline Character to a String in Java.

    To get an actual combination, do use:

    System.lineSeparator()
    

    According to your example:

    System.out.println("Hello" + System.lineSeparator() + "World!");
    System.out.println("Trying" + System.lineSeparator() + "this");
    

    Output:

    $ java Strings.java 
    Hello
    World!
    Trying
    World!
    this
    

    This is a bit ugly, but a universal solution.

    P.S. As alternative, you can use System.out.format() instead:

    System.out.format("Hello%nWorld!%n");
    System.out.format("Trying%nthis%n");
    

    P.P.S. I think in general it is better to build a list of lines and use System.out.println():

    Arrays.asList("Hello", "World!").forEach(System.out::println);
    Arrays.asList("Trying", "this!").forEach(System.out::println);