carriage return in Java
Last Updated :
24 Oct, 2023
In Java, carriage return is represented as the escape sequence \r and is used to move the cursor to the beginning of the current line without continuing to next line. When combined with \n it can be used to create a new line and move the cursor to the beginning of that new line and a combination of \r and \n is used to represent a standard newline on Windows-based systems.
Syntax of Java carriage return
String text = "Hello\rWorld!";
Parameters:
The string text will contain the value “text1” followed by carriage return and then “text2”.
Example of Java Carriage return
1. Carriage Return in a String
In this example, we have a single string with a carriage return \r and which moves the cursor back to the beginning of the line before printing “string 2”.
Below is the implementation of the above method:
Java
import java.io.*;
public class Example01 {
public static void main(String[] args) {
String text = "string 1\rstring 2" ;
System.out.println(text);
}
}
|
Output:
string 1
string 2
2. Replacing Newline with Carriage Return
In this example, we use the replaceAll() method to replace all occurrences of \n with \r\n and This allows us to convert text with newline characters into text with the carriage return and line feed suitable for the different platforms or file formats.
Below is the implementation of the above method:
Java
import java.io.*;
public class Example02 {
public static void main(String[] args)
{
String text
= "Hello Everyone.\nwelcome to GeeksforGeeks.\n" ;
String result = text.replaceAll( "\n" , "\r\n" );
System.out.println(result);
}
}
|
Output:
Hello Everyone.
welcome to GeeksforGeeks.
Share your thoughts in the comments
Please Login to comment...