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 IntToLong {
   public static void main(String[] args) {
     int a = 89;
     long c = a;
     System.out.println(c);    // 89
   }
 } 
Click Here to View the Output!
89
Click Here to View the Explanation!
  • In this program, there are two variables a and b of int type initially created.
  • Notice the expression: long c = a;
  • Since integer data type has lower precedence than the long data type, hence there is no need of explicitly converting the int variable to long type. This is performed automatically.
  • Since int values will always fall under the long range, no data loss would occur. This concept is termed as widening typecasting.

2.Convert using valueof()

Click Here to View the Solution!
public class IntToLong {
   public static void main(String[] args) {
     int a = 876;
     Long obj = Long.valueOf(a);
     System.out.println(obj); 
   }
 } 
Click Here to View the Output!
876
Click Here to View the Explanation!
  • In this program an integer variable is converted into an instance of Long (Java wrapper class).
  • Long.valueOf() method takes the integer variable a and converts it into an instance of the Long class.
%d bloggers like this: