Java Float intBitsToFloat Method

JavaJavaBeginner
Practice Now

Introduction

Java intBitsToFloat() method is a part of the Float class of the java.lang package. This method returns the float value of the integer bits value passed as argument in accordance with the IEEE 754 floating-point 'single format' bit layout. In this lab, you will learn how to use the intBitsToFloat() method in Java programming by following the below steps.

Add the Float and Scanner Packages

Add the Float and Scanner packages to the file.

import java.lang.Float;
import java.util.Scanner;

Create a Main Method

Create a main method that takes user input.

public class IntBitsToFloatLab {
    public static void main(String[] args) {
        try {
            System.out.println("Enter value:");
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            System.out.println("Float value is: " + Float.intBitsToFloat(n)); // int bits converted to float
        } catch (Exception e) {
            System.out.println("Invalid Input!!");
        }
    }
}

Compile and Run the Java File

Compile the java file using the below command in the ~/project directory:

javac IntBitsToFloatLab.java

Run the class file using the below command.

java IntBitsToFloatLab

Test the Java Program

When you run the program in the terminal, It will prompt you to enter an integer value. After entering the integer value, the program will convert the integer bits to its equivalent float value based on the IEEE 754 floating-point representation as discussed earlier.

Enter value:
84
Float value is: 1.18E-43

Test the Invalid Input

When you enter an invalid input, for example a hexadecimal value, the code will catch the exception and return an error message "Invalid Input!!".

Enter value:
0x560
Invalid Input!!

Edit the Code

You can edit the code according to your requirements to test it for different values.

import java.lang.Float;
import java.util.Scanner;

public class IntBitsToFloatLab {
    public static void main(String[] args) {
        try {
            System.out.println("Enter integer value:");
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            System.out.println("Float value is: " + Float.intBitsToFloat(n)); // int bits converted to float
        } catch (Exception e) {
            System.out.println("Invalid Input!!");
        }
    }
}

Compile and Run the Edited Code

You can run the newly edited code using the same commands we used earlier.

javac IntBitsToFloatLab.java
java IntBitsToFloatLab

Summary

Congratulations! Now you have learned how to use the intBitsToFloat() method in Java programming to convert integer bits value to its equivalent floating-point format value according to the IEEE 754 floating-point representation.

Other Java Tutorials you may like