In this java program, we will learn about how to convert a integer(int) variable into a long value.
Int is a smaller datatype and long is a larger datatype. Therefore, Java automatically converts an int value to a long value when you assign it to a long variable. When converting a smaller datatype to larger datatype, it is called widening casting.
To understand this java program, you should have understanding of the following Java programming concepts:
Java program to convert int to long using typecasting
We can convert int to long in java using assignment operator. There is nothing to do extra because lower type can be converted to higher type implicitly. In this program, int variable is automatically converted into long value.
public class IntegerToLong1 { public static void main(String[] args) { // Initialize int variable int intVal = 100; // Widening casting of int to long. long longVal = intVal; System.out.println(longVal); } }Output
100
Java program to convert int into Long Object using valueof() method
We can convert 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 object after the conversion.
public class IntegerToLong2 { public static void main(String[] args) { // Initialize int variable int intVal = 150; // Convert int to Long object Long longObj = Long.valueOf(intVal); System.out.println(longObj); } }Output
150