9

Is there any practical usage for \r and \b in Java? Could someone give an example where it's used?

aioobe
  • 413,195
  • 112
  • 811
  • 826
GrowinMan
  • 4,891
  • 12
  • 41
  • 58
  • 4
    Well, when you need to output/save those characters, it's pretty handy don't you think? – Mat Sep 11 '11 at 13:18
  • The question is not clear. The title references formfeed and backspace but the question references carriage return and backspace. – Douglas Held Jun 19 '18 at 11:22

4 Answers4

16

Formfeed escape is \f, not \r. The former is useful for clearing the screen in a console, whilst the second is useful for progress displays (as stated by aioobe).

\b can be used in progress displays also, for example, on a ICMP Ping, you could display a dot when a ping is sent and a \b when it is received to indicate the amount of packet loss.

nbro
  • 15,395
  • 32
  • 113
  • 196
squidge
  • 454
  • 2
  • 9
8

Form feed is \f and \r is carriage return. \f is used for printing characters after it from new line starting just below previous character.

System.out.println("This is before\fNow new line");
System.out.println("TEXTBEFORE\rOverlap");
System.out.println("12\b3");

Output:

This is before
          Now new line
OverlapORE
13
nkr
  • 3,026
  • 7
  • 31
  • 39
Rohan Gupta
  • 81
  • 1
  • 2
8

I usually use \r together with System.out.print when printing some progress percentage.

Try running this in your terminal:

class Test {
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            System.out.print("Progress: " + i + " %\r");
            Thread.sleep(100);
        }
    }
}
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 1
    If I use \n instead of \r , it gives me the same results , what's the difference between two ? I guess \r is obsolete now. – Praveen Kumar Dec 08 '15 at 06:15
  • 2
    See [this q/a](http://stackoverflow.com/questions/1761051/difference-between-n-and-r). – aioobe Dec 08 '15 at 07:38
3

Form feed is a page-breaking ASCII control character. It forces the printer to eject the current page and to continue printing at the top of another. Often, it will also cause a carriage return. For further details click here