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.

How to Convert int to long in Java

 

 

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.

Output

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.

Output