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 :
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
The first method uses casting, where we explicitly cast "myInt" to a "long" by using the "(long)" operator. We then assign the resulting "long" value to a new variable named "myLong1", which we print to the console using System.out.println().
The second method uses the L suffix, where we add the value of 100L to "myInt". The L suffix indicates to the compiler that the literal 100 should be treated as a "long" value. We then assign the resulting "long" value to a new variable named "myLong2", which we also print to the console using System.out.println().
Example 2 :
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
Login/Signup to comment