Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert from int to Long in Java?

I keep finding both on here and Google people having troubles going from long to int and not the other way around. Yet I'm sure I'm not the only one that has run into this scenario before going from int to Long.

The only other answers I've found were "Just set it as Long in the first place" which really doesn't address the question.

I initially tried casting but I get a "Cannot cast from int to Long"

for (int i = 0; i < myArrayList.size(); ++i ) {     content = new Content();     content.setDescription(myArrayList.get(i));     content.setSequence((Long) i);     session.save(content); } 

As you can imagine I'm a little perplexed, I'm stuck using int since some content is coming in as an ArrayList and the entity for which I'm storing this info requires the sequence number as a Long.

like image 225
Ghosty Avatar asked Aug 19 '09 21:08

Ghosty


People also ask

How do you make a long in java?

To initialize long you need to append "L" to the end. It can be either uppercase or lowercase. All the numeric values are by default int . Even when you do any operation of byte with any integer, byte is first promoted to int and then any operations are performed.

Can you convert a string to a long in java?

There are many methods for converting a String to a Long data type in Java which are as follows: Using the parseLong() method of the Long class. Using valueOf() method of long class. Using constructor of Long class.


1 Answers

Note that there is a difference between a cast to long and a cast to Long. If you cast to long (a primitive value) then it should be automatically boxed to a Long (the reference type that wraps it).

You could alternatively use new to create an instance of Long, initializing it with the int value.

like image 67
Daniel Earwicker Avatar answered Oct 20 '22 16:10

Daniel Earwicker