**Decimal to hexadecimal in java: **In the previous article, we have discussed Java Program for Decimal to Octal

In this article we will discuss about how to convert Decimal to Hexadecimal.

## Java Programs to Convert Decimal to Hexadecimal

Before jumping into the program directly, let’s first know about decimal and hexadecimal.

**Decimal:**

Decimal number mainly defines the base of 10 in the number system. This number is basically consists of 10(ten) single digits like 0,1,2,3,4,5,6,7,8 and 9 with base 10. It is also known as a position value system.

Example: (183)10 (321)10

where, (number)10 number represents the original number and 10 is the base.

**Hexadecimal:**

Hexadecimal number basically defines the base of 16 in the number system. This number is basically consists of 16(sixteen) single digits and alphabets like 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E and F. This number is represented by 4(four) bit only.

Example: (214)16 (178)16

where, (number)16 number represents the original number and 16 is the base.

Let’s see different ways convert decimal to hexadecimal.

### Method-1: Java Program for Decimal to Hexadecimal By using Integer.toHexString()

In this approach the conversion takes place directly using the method i.e. `Integer.toHexString()`

in this way when the decimal number is passed as parameter to the predefined method that directly converts into hexadecimal.

Let’s see the program to understand it more clearly.

public class DecimalToHex { public static void main(String args[]) { // for converting decimal to hexa decimal number System.out.println(Integer.toHexString(214)); System.out.println(Integer.toHexString(178)); } }

Output: d6 b2

### Method-2: Java Program for Decimal to Hexadecimal By using Custom logic method

In this approach of custom logic method, the 16 character of hexadecimal numbers are taken memory input. After that the condition is checked with the specific variable and return the hexadecimal number as output.

import java.util.*; public class DecimalToHex { public static String toHex(int decimal) { int rem; String hex=""; char hexchars[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; while(decimal>0) { rem=decimal%16; hex=hexchars[rem]+hex; decimal=decimal/16; } return hex; } public static void main(String args[]) { //Calling custom method to get the octal number of given decimal value Scanner sc = new Scanner(System.in); System.out.println("Enter a number for conversion decimal to hexadecimal = "); int n = sc.nextInt(); String pt = Integer.toHexString(n); System.out.println("Decimal to octal of "+n+" is: "+pt); } }

Output: Enter a number for conversion decimal to hexadecimal = 526 Decimal to octal of 526 is: 20e

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

**Related Java Programs:**