w3resource

Java: Check whether a given string is a valid hex code or not


26. Validate Hex Code

Write a Java program to check whether a given string is valid hex code or not.

A hexadecimal color value is a six-digit code preceded by a # sign, and is exactly 6 characters in length. Each character must be an alphabetic character from A-F (uppercase or lowercase.) or a digit from 0-9.

Sample Solution:

Java Code:

public class test {
 
   public static void main(String[] args) {	   
	    String text = "123456";
		System.out.println("Original String: "+text);
		System.out.println("Check the said string is a valid hex code or not? "+validate(text));
		text = "#eaecff";
		System.out.println("\nOriginal String: "+text);
		System.out.println("Check the said string is a valid hex code or not? "+validate(text));
		text = "#FF0000";
		System.out.println("\nOriginal String: "+text);
		System.out.println("Check the said string is a valid hex code or not? "+validate(text));
		text = "#DD5C5C";
		System.out.println("\nOriginal String: "+text);
		System.out.println("Check the said string is a valid hex code or not? "+validate(text));
		text = "#0000000";
		System.out.println("\nOriginal String: "+text);
		System.out.println("Check the said string is a valid hex code or not? "+validate(text));		
	}

   public static boolean validate(String text) {
	   return text.matches("#[0-9A-Fa-f]{6}");
   }
}

Sample Output:

Original String: 123456
Check the said string is a valid hex code or not? false

Original String: #eaecff
Check the said string is a valid hex code or not? true

Original String: #FF0000
Check the said string is a valid hex code or not? true

Original String: #DD5C5C
Check the said string is a valid hex code or not? true

Original String: #0000000
Check the said string is a valid hex code or not? false

Flowchart :

Flowchart: Last n vowels of a given string.


For more Practice: Solve these Related Problems:

  • Write a Java program to validate that a string is a proper hex color code starting with '#' followed by six hex digits.
  • Write a Java program to check if a string is a valid hex code allowing both 3-digit and 6-digit formats.
  • Write a Java program to implement a method that uses regex to confirm whether a string matches a hex code pattern.
  • Write a Java program to validate hex codes by checking both the string length and the permitted characters (0-9, A-F, a-f).

Go to:


PREV : Get Last N Vowels.

NEXT : Dash Around Vowels.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.