Convert Int Type Variables to Long in Java

Exercise:

Write a Java Program to convert int type variables to long.

1.Convert using Typecasting

Click Here to View the Solution!
public class LongToInt {
  public static void main(String[] args) {
     long a = 897787363L;
     long b = 9873653737L;
  
     int c = (int)a;
     int d = (int)b;
  
     System.out.println(c);    
     System.out.println(d);    
   }
 } 
Click Here to View the Output!
 897787363
 1283719145
Click Here to View the Explanation!
  • In this example, we have created two variables a and b which are of the long type.
  • Notice the following expression: int c = (int)a;
  • Here we are converting a variable which has higher precedence long into a variable which has lower precedence int. This is called narrowing typecasting.
  • Since the conversion is from high to low, data loss may occur if the value of the long variable exceeds the maximum range of the integer type (897787363). Otherwise no loss of data occurs and the variable is converted seamlessly.

2.Convert using toIntExact()

Click Here to View the Solution!
public class LongToInt {
   public static void main(String[] args) {
     long value1 = 987363L;
     long value2 = -7452625306L;
     int num1 = Math.toIntExact(value1);
     int num2 = Math.toIntExact(value2);
  
     System.out.println(num1);  
     System.out.println(num2);  
   }
 } 
Click Here to View the Output!
 987363
 -7452606
Click Here to View the Explanation!
  • In this program, long type variables are converted to int type variables using a Math class method toIntExact().
  • In the expression: Math.toIntExact(value1) , value1 is converted from long into integer type by the function above.
  • In case the returned int variable has a value which exceeds the integer data type’s range, then an exception occurs.

3.Convert object of the Long class to int

Click Here to View the Solution!
public class LongToInt {
   public static void main(String[] args) {
     Long obj = 7654941L;
     int a = obj.intValue();
     System.out.println(a);    
   }
 } 
Click Here to View the Output!
7654941
Click Here to View the Explanation!
  • In this program an instance of Long (Java wrapper class), is converted into an integer type. intValue() method is utilized for this operation.
  • First an instance of the class Long called obj is created, which is then converted to an integer through the intValue() method.
%d bloggers like this: