Q:

Java program to print string in hexadecimal format

belongs to collection: Java Basic Programs

0

Java program to print string in hexadecimal format

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

Program/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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to extract octets from IP address... >>
<< Java program to store the time in a single integer...