In this article, we will learn what \n and \t mean in Java.
In Java, “\n” and “\t” are called “Escape sequences”.
To understand the concept of escape sequences in detail, you can go through this tutorial.
Understanding \n in Java
Let’s assume that we want to print the following in the console.
I am in love with Escape Sequences in Java
For this, you might write the following code
public static void main(String[] args) { | |
System.out.println("I am in love with"); | |
System.out.println("Escape Sequences in Java"); | |
} |
But what if I want you to just use a single print statement.
This is where you will use \n.
In easy words \n allows you to take the cursor to the next line.
public static void main(String[] args) { | |
System.out.println("I am in love with \nEscape Sequences in Java"); | |
} |
Now, this is much more compact
Understanding \t in Java
Now, I want you to print:
I am in love with Escape Sequences in Java
The spacing between “I am in love with” and “Escape Sequences in Java” is equivalent to a tab.
To do so we need to use \t.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
In this java tutorial, we learned what does \n and \t mean in Java.
I hope this article helped you.
In case the solution is not clear to you, I suggest you take a live 1:1 lesson on this subject from me. I am an Oracle-certified tutor who would love to teach this stuff to you.
Aniket Malik