java.lang.Integer toHexString()

Description :

This java tutorial shows how to use the toHexString() method of Integer class under java.lang package. This method return a string equivalent in hexadecimal format of the int method argument.

Method Syntax :

public static String toHexString(int i)

Parameter Input :

DataType Parameter Description
int i the integer value that we want to convert into string in hexadecimal format

Method Returns :

The toHextString(int i) method simply returns the hexadecimal string equivalent of int method parameter.

Compatibility Version :

Requires Java 1.0.2 and up

Exception :

None

Discussion :

The toHexString() method is static thus we should invoke it statically for example Integer.toString(int i). This method simply converts the int parameter into hexadecimal or we could call it base 16. Make a note that counting numbers are of base 10. Normally we present hexadecimal numbers in upper case letter thus the following makes more sense Integer.toHexString(int i).toUpperCase(). We have used the method toUpperCase() of String class to transform the result in invoking the toHexString in upper case format.

The toHexString() method would yield the same result in invoking Integer.toString(int i, 16). This is just only a shortcut of calling the toString(int i,16). You might be asking when to use this method. Well, to answer this kind of concern, if you are only dealing with fix base 16, it would make sense to use the toHexStrin() because it is simpler to look at. But if you are dealing with dynamic conversion then the toString method suits better.

Java Code Example :

This java example source code demonstrates the use of delimiter() method of Scanner class. Basically it prints the delimiter that is being used by the Scanner object scan which is the default pattern since we didn’t specify delimiter to be used. The code then tokenize the String declared on the constructor of the Scanner object.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

import static java.lang.System.*;

/*
 * This example source code demonstrates the use of toHexString
 * of Integer class
 */

public class IntegerToHexString {

	public static void main(String[] args) {
		// Ask user input
		System.out.print("Number:");
		// declare the scanner object
		Scanner scan = new Scanner(System.in);
		// use scanner to get 
		int value = scan.nextInt();
		// close the scanner object
		scan.close();
		// print the value in hex format
		out.println("Hex Converted:" + Integer.toHexString(value).toUpperCase());

	}

} 

Sample Output :

Running the toHexString() method example source code of Integer class will give you the following output

Number:1234
Hex Converted:4D2

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :