How to Print Colored Text in Java Console?
Remember that in Java Programming the background color and text color of the output screen is black or white by default. If we want to Highlight some text on the output screen then we can use the ANSI color codes and highlight the particular text. One can refer to the ANSI escape code in order to explore more.
Syntax:
System.out.println(ANSI_COLORNAME + "This text is colored" + ANSI_RESET);
As perceived from the above syntax contains This Syntax contains 3 parts:
- In ANSI_COLORNAME we have to write the name in which we have given the particular ANSI code. for e.g public static final String ANSI_BLACK = “\u001B[30m”;
The above is pseudo-code is to print text in black color. So here we can use ANSI_BLACK in place of ANSI_COLORNAME to print the text in Black color.
- The second part is to write the text which we want to print in that color.
- The ANSI_RESET code turns off all ANSI attributes set so far, which should return the console to its defaults.
Below is the ANSI color code table :
Color Name |
Color code |
Background Color |
Background Color code |
BLACK |
\u001B[30m |
BLACK_BACKGROUND |
\u001B[40m |
RED |
\u001B[31m |
RED_BACKGROUND |
\u001B[41m |
GREEN |
\u001B[32m |
GREEN_BACKGROUND |
\u001B[42m |
YELLOW |
\u001B[33m |
YELLOW_BACKGROUND |
\u001B[43m |
BLUE |
\u001B[34m |
BLUE_BACKGROUND |
\u001B[44m |
PURPLE |
\u001B[35m |
PURPLE_BACKGROUND |
\u001B[45m |
CYAN |
\u001B[36m |
CYAN_BACKGROUND |
\u001B[46m |
WHITE |
\u001B[37m |
WHITE_BACKGROUND |
\u001B[47m |
Illustration: Text coloring in Java:
Example 1:
Java
import java.io.*;
public class GFG {
public static final String ANSI_RESET = "\u001B[0m" ;
public static final String ANSI_YELLOW = "\u001B[33m" ;
public static void main(String[] args)
{
System.out.println(ANSI_YELLOW
+ "This text is yellow"
+ ANSI_RESET);
}
}
|
Output:
Example 2:
Java
import java.io.*;
class GFG {
public static final String ANSI_RESET = "\u001B[0m" ;
public static final String ANSI_RED_BACKGROUND
= "\u001B[41m" ;
public static void main(String[] args)
{
System.out.println(ANSI_RED_BACKGROUND
+ "The background color is red"
+ ANSI_RESET);
}
}
|
Output:
Last Updated :
12 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...