Java Program to convert long type variables into int

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

class LongToInt {
  public static void main(String[] args) {

    // create long variables
    long a = 2322331L;
    long b = 52341241L;

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

    System.out.println(c); 
    System.out.println(d); 
  }
}
Output
2322331
52341241

Example 2: long to int conversion using toIntExact()

class LongToInt {
  public static void main(String[] args) {

    // create two long variables
    long value1 = 52133L;
    long value2 = -445436L;

    // change long to int using toIntExact() method
    int num1 = Math.toIntExact(value1);
    int num2 = Math.toIntExact(value2);

    // print the value
    System.out.println(num1); 
    System.out.println(num2);
  }
}
Output
52133
-445436

Example 3: Convert object of the Long class to int

class LongObjectToInt {
  public static void main(String[] args) {

    Long obj = 52323241L;

    // convert object of Long into int using intValue()
    int a = obj.intValue();

    System.out.println(a);   
  }
}
Output
52323241

As you know, Object Class is the super class of all the classes, you can use intValue() method on object class to concert a Long Object into int.

Leave a Reply