In this tutorial, we will see how to convert int to long with examples.
Since int is smaller data type than long, it can be converted to long with a simple assignment. This is known as implicit type casting or type promotion, compiler automatically converts smaller data type to larger data type. We can also convert int to long using valueOf() method of Long wrapper class.
Java int to long using implicit type casting
In the following example, we are simply assigning 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 type promotion.
public class JavaExample{ public static void main(String args[]){ int num = 10; /* Implicit type casting, automatic * type conversion by compiler */ long lnum = num; System.out.println(lnum); } }
Output:
Java int to long Example using Long.valueOf() method
In the following example, we are converting int to long using valueOf() method of Long Wrapper class. The valueOf() method accepts integer as an argument and returns a long value after the conversion.
public class JavaExample{ public static void main(String args[]){ int inum = 99; Long lnum = Long.valueOf(inum); System.out.println("Converted long value is: "+lnum); } }
Output:
Leave a Reply