×

Java Programs

Java Practice

Java program to print string in hexadecimal format

Given/input a string, we have to print the given string in hexadecimal format.
Submitted by Nidhi, on March 05, 2022

Problem statement

In this program, we will read a string from the user and print the input string in hexadecimal format using the "%X" format specifier in System.out.printf() method.

Source Code

The source code to print string in hexadecimal format is given below. The given program is compiled and executed successfully.

// Java program to print string in 
// hexadecimal format

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    String str;
    int i = 0;

    System.out.print("Enter string: ");
    str = SC.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 string: www.includehelp.com
Hexadecimal string: 77 77 77 2E 69 6E 63 6C 75 64 65 68 65 6C 70 2E 63 6F 6D

Explanation

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains a static method main().

The main() method is an entry point for the program. Here, we read a string from the user using the Scanner class. Then we printed the hexadecimal value corresponding to each character of string using the System.out.printf() method on the console screen.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.