Home >Java >javaTutorial >How Can I Color Console Output Using Java's System.out.println?
In console-based applications, it can be beneficial to display output in different colors to highlight important information or distinguish different data streams.
To achieve this using Java's System.out.println, we can leverage ANSI escape codes if the terminal supports them. These codes allow us to modify the color and other attributes of the output.
Firstly, define color constants using ANSI escape codes:
public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED = "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m";
To print text in a specific color, use these constants as prefixes:
System.out.println(ANSI_RED + "This text will be red!" + ANSI_RESET);
Additional Considerations:
public static final String ANSI_RED_BACKGROUND = "\u001B[41m"; System.out.println(ANSI_RED_BACKGROUND + "This text has a red background!" + ANSI_RESET);
The above is the detailed content of How Can I Color Console Output Using Java's System.out.println?. For more information, please follow other related articles on the PHP Chinese website!