How does a carriage return (\r) works in Java

Hi coders! today we are going to study a special character carriage return in Java. It is denoted by \r. Special characters are the character sequence that is used to perform a specific task. The main use of this character is to bring the cursor to the starting of the line without changing the line. It remains on the same line. All the text, written after it is put forward at the starting of the same line. It replaces the same number of old characters with new characters. Just like in Newline character (\n)  the cursor is moved to a new line.

\r or carriage return in Java

Let us understand it with the help of an example.
If we write :

System.out.print("Hello \nWorld");



Here all the letters written after \n are put in the next line. Since \n moves the cursor to the next line. Now we will see what happens when we use \r instead of \n.

System.out.print("Hello healthy \rWorld");

then the output will be:

World healthy

Here World which is a 5 letter word replaces the word Hello which is also a 5 letter word. \r does 2 kinds of work. first, it moves the cursor to the starting of the same line, and second, it replaces the same number of alphabet previously written with the same number of alphabets written after \r.

Let us look at another fun example of the above.

System.out.print("Gita is going to Market\rS ");

The output will be:

Sita is going to Market

Here S replaces G because both are of the same length which is 1. similarly a 4-alphabet word will replace Gita in the above example. Its action is similar to that of an old age typewriter. There we have to change it manually. Here we can do it with the help of a simple character sequence.

Hope you understand the topic.

Also read:

How to print Double Quotes In Java

Leave a Reply