Signup/Sign In
LAST UPDATED: OCTOBER 16, 2020

Java Integer toHexString() Method

Java toHexString() method is the part of the Integer class of the java.lang package. This method is used to return the hexadecimal equivalent of base 16 of the value passed as an unsigned integer as a String.

For example: for the value 60, the equivalent hexadecimal string returned will be CF.

Syntax:

public static String toHexString (int i)  

Parameters:

The parameter passed is the integer value of which the string representation of the equivalent hexadecimal of base 16 is to be returned.

Returns:

Returns the String representation of the parameter passed as equivalent base 16 hexadecimal value.

Example 1:

Here, a positive and a negative number is taken for a better understanding of the method.

import java.lang.Integer;

public class StudyTonight
{  
    public static void main(String[] args) 
    {          
        int i = 132; 
        int j = -52;
        System.out.println("Actual number is = " + i);  
        System.out.println("Hexadecimal equivalent is = " + Integer.toHexString(i)); //returns the integer value in hexadecimal base 16 as a string
        
        System.out.println("Actual number is = " + j);  
        System.out.println("Hexadecimal equivalent is = " + Integer.toHexString(j)); //returns the integer value in hexadecimal base 16 as a string        
    }  
} 


Actual number is = 132
Hexadecimal equivalent is = 84
Actual number is = -52
Hexadecimal equivalent is = ffffffcc

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.util.Scanner;  

public class StudyTonight
{  
    public static void main(String[] args) 
    {          
        try
        {
            System.out.print("Enter the Number = ");  
            Scanner sc = new Scanner(System.in);  
            int i = sc.nextInt();  
            System.out.println("Actual Number is  = " + i);  
            System.out.println("Hexadecimal representation is = " + Integer.toHexString(i)); //returns the integer value in hexadecimal base 16 as a string 
        }  
        catch(Exception e)
        {
            System.out.println("Invalid Number");
        }
    }
}  


Enter the Number = 674
Actual Number is = 674
Hexadecimal representation is = 2a2
******************************************
Enter the Number = -85
Actual Number is = -85
Hexadecimal representation is = ffffffab
******************************************
Enter the Number = 0x55
Invalid Number

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.