java.lang.Float intValue()

Description

The intValue() method of Float class is used to get the equivalent of this Float object in int primitive. This method is a little bit tricky to use since the float primitive can handle more precision than int value thus if we will use the this method we might lost the precision the original value has. Let’s say we have the following declaration Float value = new Float(5147483647.4847f);. Certainly the value 5147483647.4847f is still within range of Float but what will happen if we will convert it to int using intValue() method? I will be discussing this thoroughly later on this document.

Method Syntax

public int intValue()

Method Returns

The intValue() method of Float class returns the float value represented by this object converted to type int.

Compatibility

Java 1.0

Discussion

The intValue() method is used to transform this Float object to primitive int byte. This is basically the core functionality of this method. As we all know a float data type can have decimal digits, what will happen to that if we convert it to int? For example if we have the following expression: Float value = new Float(15.12f);. What will gonna happen is that, the decimal digit will get truncated if we use the intValue method. What we mean we say the decimal digit will get truncated such that the value returned will be be 15.

Java Float intValue() Example

Below is a simple java example on the usage of intValue() method of Float class.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

import static java.lang.System.*;

/*
 * This example source code demonstrates the use of 
 * intValue() method of Float class.
 */

public class FloatIntValueExample {

	public static void main(String[] args) {
		
		// Ask user input
		System.out.print("Enter Desired Value:");
		// declare the scanner object
		Scanner scan = new Scanner(System.in);
		// use scanner to get value from user console
		Float userInput = scan.nextFloat();
		// close the scanner object
		scan.close();		
		// convert the Float input to int
		int value = userInput.intValue();
		out.println("Value in int is " + value);
		
	}

}

Basically on the above example, we just ask for user input on the console and then we use the scanner object to get the float input. After that we assign the value to an Float wrapper class and we then get the value in primitive data type int using the intValue() method of Float class.

Sample Output

Below is the sample output when you run the above example.

Float intValue() Sample Output