ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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.

Java Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.