Given a number of int datatype in Java, your task is to write a Java program to convert this given int datatype into a long datatype.
Example:
Input: intnum = 5 Output: longnum = 5 Input: intnum = 56 Output: longnum = 56
Int is a smaller data type than long. Int is a 32-bit integer while long is a 64-bit integer. They both are primitive data types and the usage depends on how large the number is.
Java int can be converted to long in two simple ways:
- Using a simple assignment. This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types.
- Using valueOf() method of the Long wrapper class in java which converts int to long.
- In this, we are simply assigning an integer data type to a long data type.
- Since integer is a smaller data type compared to long, the compiler automatically converts int to long, this is known as Implicit type casting or type promotion.
Java
// Java program to demonstrate // use of implicit type casting Â
import java.io.*; import java.util.*; class GFG { Â Â Â Â public static void main(String[] args) Â Â Â Â { Â Â Â Â Â Â Â Â int intnum = 5 ; Â
        // Implicit type casting , automatic         // type conversion by compiler         long longnum = intnum; Â
        // printing the data-type of longnum         System.out.println(             "Converted type : "             + ((Object)longnum).getClass().getName()); Â
        System.out.println( "After converting into long:" );         System.out.println(longnum);     } } |
Converted type : java.lang.Long After converting into long: 5
2. Â Long.valueOf() method:
- In this, we are converting int to long using the valueOf() method of the Long Wrapper class.
- The valueOf() method accepts an integer as an argument and returns a long value after the conversion.
Java
// Java program to convert // int to long using valueOf() method Â
import java.io.*; Â
class GFG { Â Â Â Â public static void main(String[] args) Â Â Â Â { Â Â Â Â Â Â Â Â int intnum = 56 ; Â Â Â Â Â Â Â Â Long longnum = Long.valueOf(intnum); Â
        // printing the datatype to         // show longnum is of type         // long contains data of intnum         System.out.println(             "Converted type : "             + ((Object)longnum).getClass().getName()); Â
        // accepts integer and         // returns a long value         System.out.println( "After converting into long:"                            + "\n" + longnum);     } } |
Converted type : java.lang.Long After converting into long: 56