Google News
logo
Java Program to convert int type variables to long
In the following examples of Java program convert integer (int) variables into the long variables.

Example 1: Java Program to Convert int to long using Typecasting :

Program :
class Main {
  public static void main(String[] args) {

    // create int variables
    int a = 25;
    int b = 34;

    // convert int into long
    // using typecasting
    long c = a;
    long d = b;

    System.out.println(c);    // 25
    System.out.println(d);    // 34
  }
}
Output :
25
34
Here, the int type variable is automatically converted into long. It is because long is a higher data type and int is a lower data type.

Hence, there will be no loss in data while converting from int to long. This is called widening typecasting.

Example 2: Java Program to Convert int into object of Long using valueof() :

We can convert the int type variable into an object of the Long class. For example,
Program :
class Main {
  public static void main(String[] args) {

    // create int variables
    int a = 251;

    // convert to an object of Long
    // using valueOf()
    Long obj = Long.valueOf(a);

    System.out.println(obj);    // 251
  }
}
Output :
251
In the above example, we have used the Long.valueOf() method to convert the variable a into an object of Long.

Here, Long is a wrapper class in Java.