# Java program to convert Decimal into Hexadecimal

This program is used to convert a decimal number into a hexadecimal number in Java.
A Decimal number employs 10 as a base and represents any number using 10 digits [0-9].
While
A Hexadecimal number employs 16 as a base and represent any number using 10 digits and 6 characters [0-9,A,B,C,D,E,F].

Hence, we can say we need to convert a number with base value 10 to base value 16.

There are 2 ways to convert a Decimal number to Hexadecimal number:

1. Using the Integer.toHexString() method.
2. Using our own logic to implement it unlike the predefined method in the above step.

## Integer.toHexString() method to get Hexadecimal from Decimal

```import java.io.*;
class DecimalToHex
{
public static void main(String args[])throws IOException
{
int n; //Defining decimal number
System.out.println("Enter a decimal number: ");
n = Integer.parseInt(br.readLine()); //Entering the decimal number
String hex= Integer.toHexString(n); //Using the predefined function
System.out.println("The corresponding hexadecimal number is: "+hex); //Getting the required output
}
}
```

As shown above, the code is easily explained and easy to understand and implement.
It gives the following outputs for different inputs:

```1)
Enter a decimal number:
14
The corresponding hexadecimal number is: e```
```2)
Enter a decimal number:
26
The corresponding hexadecimal number is: 1a```
```3)
Enter a decimal number:
289
The corresponding hexadecimal number is: 121```

## Another way to convert Decimal into Hexadecimal in Java

```import java.io.*;
class DecimalToHex
{
public static void main(String args[])throws IOException
{
int n,rem;
String hexa=""; //rem is to store the remainder and hexa is to store the hexadecimal
System.out.println("Enter a decimal number: ");
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};  //digits in hexadecimal system
while(n>0)
{
rem=n%16;
hexa=hex[rem]+hexa;
n=n/16;
}
System.out.println("The corresponding hexadecimal number is: "+hexa);
}
}
```

As shown above, we have not used any predefined functions and solved it using our own logic simply by using arrays and while loop.
It gives the following output: (similar to the first way)

```1)
Enter a decimal number:
14
The corresponding hexadecimal number is: e```
```2)
Enter a decimal number:
26
The corresponding hexadecimal number is: 1a
```

Also learn: