Is there any practical usage for \r and \b in Java? Could someone give an example where it's used?
-
4Well, 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 Answers
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.
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);
}
}
}
- 399,198
- 105
- 792
- 807
-
1If 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
-
2See [this q/a](http://stackoverflow.com/questions/1761051/difference-between-n-and-r). – aioobe Dec 08 '15 at 07:38
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
- 2,987
- 7
- 30
- 39
- 61
- 1
- 2
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
- 29
- 1