Java Integer.toHexString() – Examples
In this tutorial, we will learn about Java Integer.toHexString() method, and learn how to use this method to find the hexadecimal representation of given integer, with the help of examples.
toHexString(int i)
Integer.toHexString() returns a string representation of the integer argument as an unsigned integer in base 16.
The digits in a hexadecimal string are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
Syntax
The syntax of toHexString() method with an integer as parameter is
Integer.toHexString(int i)
where
Parameter | Description |
---|---|
i | The integer whose hexadecimal representation has to be found. |
Returns
The method returns value of type String.
Example 1 – toHexString()
In this example, we will take an integer and find its hexadecimal representation using Integer.toHexString() method.
Java Program
public class Example {
public static void main(String[] args){
int i = 31;
String result = Integer.toHexString(i);
System.out.println("Result of toHexString("+i+") = " + result);
}
}
Output
Result of toHexString(31) = 1f
Example 2 – toHexString() – Negative Integer
In this example, we will take a negative integer and find its hexadecimal representation using Integer.toHexString() method. Since, the integer is negative, and considered as an unsigned integer in base 16 by the method, we get the complement form of the integer.
Java Program
public class Example {
public static void main(String[] args){
int i = -31;
String result = Integer.toHexString(i);
System.out.println("Result of toHexString("+i+") = " + result);
}
}
Output
Result of toHexString(-31) = ffffffe1
Conclusion
In this Java Tutorial, we have learnt the syntax of Java Integer.toHexString() method, and also how to use this method with the help of Java example programs.