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.
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|
Illustration: Text coloring in Java:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.