Horje
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 GeeksforGeeks.\n";
        
        String result = text.replaceAll("\n", "\r\n");
        System.out.println(result);
    }
}

Output:

Hello Everyone.
welcome to GeeksforGeeks.




Reffered: https://www.geeksforgeeks.org


Java

Related
How to Create a Banner Using Applet? How to Create a Banner Using Applet?
Diamond Problem in Java Diamond Problem in Java
Create Bingo Game Using Java Create Bingo Game Using Java
Java Program to Convert Boolean to String Java Program to Convert Boolean to String
Java File Handling Programs Java File Handling Programs

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15