Have you ever thought of coloring the output on the console through Java? Well, recently I wanted to color my console output and I've got the program working finally after a bit of research.

Just to give you a bit of background about consoles, each console vendor used to have their own standards in the early days. And ANSI had finally introduced a standard for consoles to interpret the colors, positions, control characters etc. You can read more about ANSI escape codes on wiki.

As per the ANSI standard all the instructions to interpret the color and positions should follow below syntax:

Escape_character[<<code>>m <<output text>>
  • Output text is the output that should be printed on the console
  • Code represents the effect that should take place on console. Refer below table (Note, I'm giving only very commonly used codes here)
Code Effect
0 Reset all the formatting
1 Bold
3 Italics
4 Underline
30-37 Each number represents one colors i.e.; 30 is for Black, 31 for Red, 32 for Green, 33 for Yellow etc.

Note: DOS doesn't support ANSI colors. You can use Linux terminal or Netbeans IDE to run this program. And Escape character in Java is ASCII code 33 (i.e.; \033)

Coloring.java
/**
* Demonstrating console colring
* @author SANTHOSH REDDY MANDADI
* @version 1.0
* @since 06-June-2013
*/
public class Coloring
{
public static void main(String args[])
{
System.out.println("\033[31;1mHello\033[0m, \033[32;1;2mworld!\033[0m");
System.out.println("\033[31mRed\033[32m, Green\033[33m, Yellow\033[34m, Blue\033[0m");
}
}
Output
Hello, world!
Red, Green, Yellow, Blue