1. Using \t as the string
2. Using \t as character
Read Also: What does \t mean in Java
Let's dive deep into the topic:
How to print tab space in Java
Below are some examples of printing tab space in Java:1. Using \t as the string
In the below example, we are printing two strings by using a simple "\t" symbol. public class PrintTabSpace {
public static void main(String args[]) {
// Printing Tab at the start of the given string
String s1 = "\t"+"Alive is awesome";
System.out.println(s1);
// Printing Tab in the middle of the given string
String s2 = "Love"+"\t"+"Yourself";
System.out.println(s2);
// Printing Tab at the end of the given string
String s3 = "Be in present"+"\t";
System.out.println(s3);
}
}
Output:
Alive is awesome
Love Yourself
Be in present
2. Using \t as character
In the below example, we are printing given string with tab space by using '\t' as the character. public class PrintTabSpace2 {
public static void main(String args[]) {
// Another way of printing tab at the start of the given string
String str1 = "\tAlive is awesome";
System.out.println(str1);
// Another way of printing tab in the middle of the given string
String str2 = "Love\tYourself";
System.out.println(str2);
// Another way of printing tab at the end of the given string
String str3 = "Be in present\t";
System.out.println(str3);
}
}
Output:
Alive is awesome
Love Yourself
Be in present
3. Using \t multiple times
In the below example, we will see how to print two strings with multiple tabs(more than one tab). public class PrintTabSpace3 {
public static void main(String args[]) {
// Printing multiple tabs at the start of the given string
String strobj1 = "\t\t\tBe in Present";
System.out.println(strobj1);
// Printing multiple tabs in the middle of the given string
String strobj2 = "Love"+"\t\t\t\t\t"+"Yourself";
System.out.println(strobj2);
// Printing multiple tabs at the end of the given string
String strobj3 = "Alive is Awesome"+"\t\t";
System.out.println(strobj3);
}
}
Output:
Be in present
Love Yourself
Alive is awesome
How many spaces contains in a tab(\t)
Most code editors(e.g. Eclipse, IntelliJ) allow you to use TAB(\t) characters in your source code. TAB characters are inherently ambiguous in Java which leads to the problem. The problem is that different tools show TAB characters in different ways. In short, TAB can contain 2, 4, or 8 spaces. The best practice is to prefer spaces over tabs for code indentation.That's all for today. Please mention in the comments in case you have any questions related to how to print the tab space in Java.