Java Program to Convert int to long

Java Program to Convert int to long

What is int in Java ?

“int” is a primitive data type in Java that is used to represent integers (whole numbers) within a certain range of values. The range of values that can be stored by an “int” is from -2^31 to 2^31-1. The “int” data type is commonly used in mathematical operations and to represent arrays of integers.

What is long in Java ?

In Java, “long” is a primitive data type used to represent integer values that are larger than the range of “int” data type.

The “long” data type is a 64-bit two’s complement integer, which means it can hold values between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 inclusive. The keyword to declare a variable of type “long” is simply “long”.

Ways to Convert int to long  : 

Syntax :

int myInt = 123;
long myLong = (long) myInt;

Syntax :

int myInt = 123;
long myLong = myInt + 100L;

Syntax :

int myInt = 123;
long myLong = Long.valueOf(myInt);

Example 1 : 

Run

public class Main {
    public static void main(String[] args) {
        int myInt = 123;
        
        // Using casting to convert int to long
        long myLong1 = (long) myInt;
        System.out.println("Using casting: " + myLong1);

        // Using L suffix to convert int to long
        long myLong2 = myInt + 100L;
        System.out.println("Using L suffix: " + myLong2);
    }
}

Output :

Using casting: 123
Using L suffix: 223

Example 2 : 

Run

public class Main {
    public static void main(String[] args) {
        int myInt = 123;
        
        // Using valueOf() method to convert int to long
        Long myLong1 = Long.valueOf(myInt);
        System.out.println("Using valueOf() method: " + myLong1);

      
    }
}

Output :

Using valueOf() method: 123

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription