How to Convert int to long in Java
How to Convert int to long in Java
When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to common data type before evaluating the expression. Java compiler follows certain rules to decide which variable’s data type is to be converted. It converts the lower data type to that of a higher data type. This conversion is called widening a type or implicit conversion or type promotion. int occupies 4 bytes and long occupies 8 bytes in the memory.

There are two ways to convert int to long.
- Using Assignment Operator
- Using valueOf() method
Using Assignment Operator
We can convert int to long conversion by using assignment operator.
Example
In the following example, we have taken a variable sum of type int and initialize 20 into it. Now we assign sum variable to the variable l of type long. It converts int to long implicitly and then stores the long value to l. The first println statement prints the integer value of sum and the second println statement prints the long value of the variable sum.
public class intTolongExample { public static void main(String args[]) { int sum = 20; // 4 bytes long l = sum; // 4 bytes assigned to 8 bytes System.out.println("int value: " +sum); System.out.println("Converted long value: " + l); } }
Output
int value: 20 Converted long value: 20
Using Long.valueOf() method
We can also convert int to long by using valueOf() method of the Long wrapper class. The valueOf() method parses integer as an argument and returns a long value after the conversion.
Example
In the following example, avg is a variable of type int and we assigned 12 to it. valueOf() is the method of Long wrapper class that parses avg as an argument and returns the long value after conversion. num is a variable that stores the converted long value. The println statement prints the long value of the variable avg.
public class intTolongExample1 { public static void main(String args[]){ int avg = 12; long num = Long.valueOf(avg); System.out.println("Converted long value of avg is: "+num); } }
Output
Converted long value of avg is: 12