Here we are going to write a program on conversion of Decimal To Hex Numbers in Java.
Decimal To Hex Conversion :
ConvertDecimalToHexaDecimal.java
import java.util.Scanner;
public class ConvertDecimalToHexaDecimal {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter any Decimal Number : ");
int input = sc.nextInt();
System.out.println(" Hex : " + convertDecimalToHexaDecimal(input));
}
public static String convertDecimalToHexaDecimal(int decimal) {
String hexaDecimal = "";
String hex = "0123456789ABCDEF";
try {
if (decimal != 0) {
while (decimal > 0) {
hexaDecimal = hex.charAt(decimal % 16) + hexaDecimal;
decimal /= 16;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
hex = null;
}
return hexaDecimal;
}
}
Output :
Enter any Decimal Number : 505
Hex : 1F9
Happy Learning 🙂