Carriage Return in java with examples.

In this tutorial, we will learn Carriage Return in Java and its application with example programs.

Carriage return (\r) is a control character used to reset the position of the cursor to the beginning of the line without advancing to the next line. In Java, it’s commonly used in console applications to overwrite the current line of output.

 

Understanding Carriage Return

The carriage return character, represented as ‘\r ‘ in Java, moves the cursor to the beginning of the current line. When printing text after a carriage return, the new text will overwrite the existing content on that line.

Basic Usage

Let’s understand how ‘\r’ works with a simple example:

public class CarriageReturn
{
    public static void main(String[] args) 
    {
        System.out.println("--Before using carriage return : ");
        System.out.println("Hello, Welcome to CodeSpeedy");
        System.out.println("--After using carriage return : ");
        System.out.println("Hello, Welcome to \rCodeSpeedy");
    }
}

Output:

--Before using carriage return :
Hello, Welcome to CodeSpeedy
--After using carriage return :
CodeSpeedycome to

In the above example program, the characters “Hello, Wel” are overwritten by the characters “CodeSpeedy” because of using “\r” before CodeSpeedy.

Overwriting Console Output

Carriage return is often used to create dynamic updates in the console, such as progress bars or real-time status updates.

Example: Simple Progress Indicator

public class ProgressBar
 {
    public static void main(String[] args) throws InterruptedException 
    {
        for (int i = 0; i <= 100; i++) 
        {
            System.out.print("\rLoading: " + i + "%");
            Thread.sleep(100); // Pause for 100 milliseconds
        }
        System.out.println(); // Move to the next line after completion
    }
}

Output: Dynamic Progress Bar output

 

Example Use Cases

Real-Time Status Updates

Carriage return is useful for real-time status updates in command-line applications, such as showing the current time or countdowns.

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
        while (true) {
            System.out.print("\rCurrent Time: " + LocalTime.now().format(dtf));
            Thread.sleep(1000); // Update every second
        }
    }
}


Output:

Current Time: 16:22:15

This example displays the current time, updating every second in the same position in the console.

Progress Bars

Carriage return is often used to create progress bars in the console.

public class ProgressBar 
{
    public static void main(String[] args) throws InterruptedException 
    {
        int total = 100;
        for (int i = 0; i <= total; i++) 
        {
            StringBuilder progress = new StringBuilder("[");
            for (int j = 0; j < total; j++)
            {
                if (j < i) 
                {
                    progress.append("-");
                }
                else 
                {
                    progress.append(" ");
                }
            }
            progress.append("] " + i  + "%");
            System.out.print("\r" + progress);
            Thread.sleep(100);
         } 
         System.out.println();   
    }
}
Output:

StringBuilder Class in Java

Conclusion

Carriage return (\r) is a powerful tool for creating dynamic and real-time outputs in console applications.

This is how Carriage Return is used in Java.

Hope you liked my Explanation.

“HAPPY CODING”

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top