What is the correct way to convert int to long in Java?
I often find people discussing the issues of converting long to int, but not the other way around. However, I’m sure I’m not the only one who has needed to convert an int to a Long.
I initially tried casting, but I got an error: “Cannot cast from int to Long”.
For example, in my loop:
for (int i = 0; i < myArrayList.size(); ++i ) {
content = new Content();
content.setDescription(myArrayList.get(i));
content.setSequence((Long) i); // Error here
session.save(content);
}
Since I have to use int because the data comes from an ArrayList, but the entity requires Long, how should I properly convert int to long in Java?
I’ve worked with Java for a while, and converting int
to long
is pretty straightforward, but I get why the (Long) i
cast might trip you up—it doesn’t work because Long
is an object (wrapper class), while int
is a primitive type. No worries though! In Java, int
can be automatically promoted to long
because long
has a wider range. So, you don’t even need an explicit cast:
for (int i = 0; i < myArrayList.size(); ++i) {
content = new Content();
content.setDescription(myArrayList.get(i));
long sequence = i; // Implicit conversion
content.setSequence(sequence);
session.save(content);
}
Why use this?
- No explicit casting required.
- Java automatically promotes
int
to long
.
- Works for all
long
values (except Long
objects, which we’ll get to next).
Building on @Rashmihasija’s point, if you’re dealing with methods or collections that specifically require a Long
object (not just a long
primitive), you’ll need to convert the int
to a Long
. One easy way is by using Long.valueOf()
: "*
for (int i = 0; i < myArrayList.size(); ++i) {
content = new Content();
content.setDescription(myArrayList.get(i));
content.setSequence(Long.valueOf(i)); // Converts int to Long object
session.save(content);
}
Why use this?
- Explicitly converts
int
to a Long
object, preventing type mismatch errors.
- Useful when working with Java collections or APIs that require
Long
instead of long
.
- Ensures compatibility with frameworks like Hibernate or Spring Data.
To add to @vindhya.rddy’s solution, there’s another (albeit less efficient) way to convert int
to Long
—by using the new Long()
constructor. While it works, it’s not recommended anymore due to its inefficiency. Still, it’s worth mentioning for completeness:
for (int i = 0; i < myArrayList.size(); ++i) {
content = new Content();
content.setDescription(myArrayList.get(i));
content.setSequence(new Long(i)); // Not recommended but valid
session.save(content);
}
Why use this?
- This manually boxes the
int
into a Long
object.
- However, it creates a new
Long
instance each time, making it less efficient than Long.valueOf()
.
- Only use this if you’re working with older Java versions (pre-Java 5), where
Long.valueOf()
might not be available.