Objectives :
- How to convert Decimal to Hexadecimal in Java?
Java Program to convert Decimal values to Hexadecimal values :
[sourcecode lang=”java”]
import java.util.Scanner;
public class DecimalToHexadecimal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter decimal number you like: ");
int deci = input.nextInt();
System.out.println("The hexadecimal number for decimal "
+ deci + " is " + convert(deci));
}
public static String convert(int decimal) {
String hex = "";
while (decimal != 0) {
int hexValue = decimal % 16;
hex = toHexadecimal(hexValue) + hex;
decimal = decimal / 16;
}
return hex;
}
public static char toHexadecimal(int hexValue) {
if (hexValue <= 9 && hexValue >= 0) {
return (char) (hexValue + ‘0’);
} else {
return (char) (hexValue – 10 + ‘A’);
}
}
}
[/sourcecode]
Output :
Enter decimal number you like: 1234
The hexadecimal number for decimal 1234 is 4D2