How to Convert long to int in Java

How to Convert long to int in Java

When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion. The conversion from long to int is called explicit conversion or narrowing conversion. long is a larger data type than int.

How to Convert long to int in Java

 

 

There are two ways to convert long to int.

  • Using Assignment Operator
  • Using intValue() method

Using Assignment Operator

Casting is used to perform the conversion between two incompatible types.  A cast is simply an explicit type conversion. The syntax of the casting is:

Example

In the following example, num1 is a variable of type long contains value 10000. num2 is a variable of type int that stores the converted int value of num1. (int)num1 converts the long value to int value. The println statement prints the converted int value of the variable num1.

Output

Using intValue() method

intValue() is the built-in method of Integer wrapper class which belongs to java.lang package. This method does not accept any parameter. It returns the value which is represented by the object after conversion to the integer type. The signature of the method is given below:

Example

In the following example, Long is the wrapper class and number is a reference variable of the class. num is the variable of type int that stores the converted value of the variable number. intValue() is the method of Integer wrapper class. The println statement prints the converted int value of the variable number.

Output