The intValue() is an inbuilt method provided by the abstract class java.lang.Number. This method converts a numeric object, such as Float, Double, etc., to an int type. This method may involve rounding or truncation if the original number is a floating-point value.
Syntax of Number.intValue() Method
public abstract int intValue()
- Parameters: This method does not accept any parameters.
- Return value: This method returns the numeric value represented by this object after conversion to type int.
Examples of Java Number.intValue() Method
Example 1: In this example, we are going to convert a Float and Double object into an int using the intValue() method.
// Java program to demonstrate Number.intValue() method
import java.lang.Number;
public class Geeks {
public static void main(String[] args) {
// Create a Float object
Float f = new Float(456f);
// Convert Float to int
System.out.println("Float to int: " + f.intValue());
// Create a Double object
Double d = new Double(20.99);
// Convert Double to int
System.out.println("Double to int: " + d.intValue());
}
}
Output
Float to int: 456 Double to int: 20
Example 2: In this example, we are using floating-point numbers with decimal parts and observing how the decimal portion is truncated during conversion.
// Java program to demonstrate
// Number.intValue() with decimals
import java.lang.Number;
public class Geeks {
public static void main(String[] args) {
// Float with decimal value
Float f = new Float(56.78f);
System.out.println("Float to int: "
+ f.intValue());
// Double with decimal value
Double d = new Double(76.9);
System.out.println("Double to int: "
+ d.intValue());
}
}
Output
Float to int: 56 Double to int: 76
Important Points:
- The intValue() method is mostly used to extract integer values from numeric objects like Float, Double, and more. It is very helpful when we want to truncate decimal digits and work with pure integers.
- Use this method carefully in scenarios where losing decimal precision is acceptable.