Java Program to convert int type variables to long

To understand this example, you should have the knowledge of the following Java programming topics:


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

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
  }
}

In the above example, we have int type variables a and b. Notice the lines,

long c = a;

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. To learn more, visit Java 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,

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
  }
}

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. To learn more, visit the Java Wrapper Class.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges