Using \n and \r characters
In this step, we will learn how to use the platform-dependent newline characters \n and \r to add a new line to a string.
Add the following code to the NewLineCharacter.java
file:
public class NewLineCharacter {
public static void main(String args[]) {
String str1 = "Java is awesome";
String str2 = "Java\nis\nawesome";
String str3 = "Java\ris\rawesome";
System.out.print(str1 + "\n" + str2 + "\n" + str3);
}
}
In the code above, we have defined three strings: str1
, str2
, and str3
. In str2
, we have used the \n character to add a new line. In str3
, we have used the \r character to add a new line.
Compile and run the program in the terminal:
javac NewLineCharacter.java && java NewLineCharacter
The program will output:
Java is awesome
Java
is
awesome
Java
is
awesome