carriage return in Java
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
// Java Program to demonstrate // Carriage Return in a String import java.io.*; // Driver Class public class Example01 { // main function 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
// Java Program to demonstrate // Replacing Newline with Carriage Return import java.io.*; // Driver Class public class Example02 { // main function public static void main(String[] args) { String text = "Hello Everyone.\nwelcome to w3wiki.\n" ; String result = text.replaceAll( "\n" , "\r\n" ); System.out.println(result); } } |
Output:
Hello Everyone.
welcome to w3wiki.