Skip to content
Related Articles

Related Articles

Java Program to Convert int to long
  • Last Updated : 27 Nov, 2020

Int is a smaller data type than long. Int is a 32-bit integer while long is a 64-bit integer. They both are primitive data types and the usage depends on how large the number is.

Example:

Input: intnum = 5
Output: longnum = 5

Input: intnum = 56
Output: longnum = 56

Int can be converted to long in two simple ways:

  1. Using a simple assignment. This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types.
  2. Using valueOf() method of the Long wrapper class in java which converts int to long.

1.  Implicit type casting

  • In this, we are simply assigning an integer data type to a long data type.
  • Since integer is a smaller data type compared to long, the compiler automatically converts int to long, this is known as Implicit type casting or type promotion.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// use of implicit type casting
  
import java.io.*;
import java.util.*;
class GFG {
    public static void main(String[] args)
    {
        int intnum = 5;
  
        // Implicit type casting , automatic
        // type conversion by compiler
        long longnum = intnum;
  
        // printin the data-type of longnum
        System.out.println(
            "Converted type : "
            + ((Object)longnum).getClass().getName());
  
        System.out.println("After converting into long:");
        System.out.println(longnum);
    }
}

chevron_right


Output



Converted type : java.lang.Long
After converting into long:
5

2.  Long.valueOf() method:

  • In this, we are converting int to long using valueOf() method of Long Wrapper class.
  • The valueOf() method accepts an integer as an argument and returns a long value after the conversion.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to convert
// int to long using valueOf() method
  
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        int intnum = 56;
        Long longnum = Long.valueOf(intnum);
  
        // printing the datatype to
        // show longnum is of type
        // long contains data of intnum
        System.out.println(
            "Converted type : "
            + ((Object)longnum).getClass().getName());
  
        // accepts integer and
        // returns a long value
        System.out.println("After converting into long:"
                           + "\n" + longnum);
    }
}

chevron_right


Output

Converted type : java.lang.Long
After converting into long:
56

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :