Objectives :
- How to convert Decimal to Hexadecimal in Java?
1: import java.util.Scanner;
2:
3: public class DecimalToHexadecimal {
4:
5: public static void main(String[] args) {
6:
7: Scanner input = new Scanner(System.in);
8:
9: System.out.print("Enter decimal number you like: ");
10: int deci = input.nextInt();
11:
12: System.out.println("The hexadecimal number for decimal "
13: + deci + " is " + convert(deci));
14: }
15:
16: public static String convert(int decimal) {
17: String hex = "";
18:
19: while (decimal != 0) {
20: int hexValue = decimal % 16;
21: hex = toHexadecimal(hexValue) + hex;
22: decimal = decimal / 16;
23: }
24:
25: return hex;
26: }
27:
28: public static char toHexadecimal(int hexValue) {
29: if (hexValue <= 9 && hexValue >= 0) {
30: return (char) (hexValue + '0');
31: } else {
32: return (char) (hexValue - 10 + 'A');
33: }
34: }
35: }
Output :
Enter decimal number you like: 1234
The hexadecimal number for decimal 1234 is 4D2
Arrange Java Workshop in your campus, visit here for details or write us here.
Labels: Aatul Palandurkar, Atul Palandurkar, Features of Java, Java, Java Tutorial, Java Tutorials, Java Tutorials for beginners