Write Java program to Print string in hexadecimal format


This Java program prompts the user to input a string and then converts each character of the string to its corresponding hexadecimal value using the printf() method. Here's how the program works:

  • The program begins by importing the Scanner class and defining a public class called String_Hexadecimal.
  • In the main method, a new Scanner object is created to read user input, a string variable called "str" is defined, and an integer variable called "i" is set to 0.
  • The user is prompted to enter a string using the System.out.print() method and the input.next() method is used to read the input and store it in the "str" variable.
  • The program then prints "Hexadecimal String : " using the System.out.print() method.
  • The for loop iterates over each character of the string using the str.length() method as the loop condition.
  • The printf() method is used to print the hexadecimal value of each character in the string using the format specifier "%02X". This will ensure that each hexadecimal value is printed using 2 digits and with leading zeroes if necessary.
  • Finally, a new line is printed using the System.out.println() method.

Source Code

import java.util.Scanner;
public class String_Hexadecimal
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		String str;
		int i = 0;
		System.out.print("Enter the String : ");
		str = input.next();
		System.out.print("Hexadecimal String : ");
 
		for (i = 0; i < str.length(); i++) 
		{
			System.out.printf("%02X ", (int) str.charAt(i));
		}
		System.out.println();
	}
}

Output

Enter the String : Java
Hexadecimal String : 4A 61 76 61

Example Programs