How to Convert Hex to String in Java

Converting Hex to String in Java

In this example, we will show you the simple program about, how to convert hex to string in Java. The example program has been tested and shared in the same post.

Example Program (Converter.java)

package com.dineshkrish;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class Converter {

	public static String convert(String hex) {

		byte[] bytes = null;

		String output = null;

		try {

			bytes = Hex.decodeHex(hex.toCharArray());

			output = new String(bytes, "UTF-8");

		} catch (DecoderException e) {

			System.out.println(e.getMessage());
			
		} catch (UnsupportedEncodingException e) {

			System.out.println(e.getMessage());
			
		}

		return output;
	}

	public static void main(String[] args) {
		
		String input = "44696e657368204b726973686e616e";
		
		String output = convert(input);

		System.out.println("Converted ---> "+output);
	}

}

Maven Dependencies (pom.xml)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.dineshkrish</groupId>
	<artifactId>Converter</artifactId>
	<version>1.0</version>

	<dependencies>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.10</version>
		</dependency>
	</dependencies>

</project>

Outpuut

Converted ---> Dinesh Krishnan
Hello everyone, I am a Founder of dineshkrish.com.