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

Time:12-06

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 VS Code, same results. Does anyone know what's going on here?

Thanks!

———

Edits:

I tried to execute something similar to (this)[https://www.w3schools.com/java/tryjava.asp?filename=demo_strings_r]. I know I don’t have to use \r at all; I just wonder why the outputs are the way they are.

CodePudding user response:

You can also use format with %n which is replaced by the platform line separator, so could use this:

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

CodePudding user response:

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);
  • Related