256

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.

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
Ghosty
  • 3,203
  • 2
  • 18
  • 13

14 Answers14

265

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.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
  • 39
    To demonstrate what Earwicker said you could call Long.valueOf(i), which takes a long but will widen an int and give you back a Long object. – Grundlefleck Aug 19 '09 at 21:08
  • 2
    Autoboxing is preferable, because it doesn't necessarily have to create a new `Long` object every time. – Michael Myers Aug 19 '09 at 21:08
  • 2
    (Warning: the rest of this comment is guesswork and conjecture) If the values given to Long.valueOf() fall between 0 and 128, which is very common, and it returns a cached instance, will that be preferable over autoboxing? (I may ask a new question if you think it's worth it...) – Grundlefleck Aug 19 '09 at 21:12
  • 4
    Autoboxing does the same thing as that. By the way, it's between -127 and 128. – Daniel Earwicker Aug 19 '09 at 21:14
  • 6
    @Grundlefleck: Autoboxing uses `Long.valueOf()` (if I remember correctly), so there wouldn't be a difference at all. My comment was in reply to the answer, not to your comment. – Michael Myers Aug 19 '09 at 21:15
  • And watch out for accidentally writing `a == b` to compare two boxed values! Will appear to work if they're in the "interning" range, will fail if not. And the range is a *minimum* of -128 to 127, but may be larger. (I think that's right, looks like I typed it the wrong way round in my last comment). – Daniel Earwicker Aug 19 '09 at 21:17
  • @mmyers: ah I see, cheers. @Earwicker: may I be so bold to suggest there's some information in these comments that would earn your answer at least another +1 were it to be included? :-) – Grundlefleck Aug 19 '09 at 21:22
  • @Grundlefleck - thanks, but would probably make more sense on a question about what autoboxing is equivalent to, e.g. you could upvote this answer: http://stackoverflow.com/questions/766468/autoboxing-so-i-can-write-integer-i-0-instead-of-integer-i-new-integer0/767167#767167 – Daniel Earwicker Aug 19 '09 at 21:39
228

Use the following: Long.valueOf(int);.

serg
  • 109,619
  • 77
  • 317
  • 330
  • 5
    Look out, as this will generate a NullPointerException if you are receiving a Integer object which is null. – will824 Oct 04 '11 at 21:57
  • 2
    correct if am wron i thought may be the answer is old becuse i cant find the method `Long.valueOf(int) !!` – shareef Jun 01 '14 at 07:21
  • 10
    @will824 - a primitive 'int' variable cannot be null. – Rondo Nov 27 '14 at 00:57
  • 1
    @shareef - see serg's comment - but I think this method casts the int to a long which autoboxes with a Long... so seems redundant – Rondo Nov 27 '14 at 01:01
  • 1
    @Rondo an `Integer` can, which is what he said. – Salem Apr 08 '17 at 09:46
  • 1
    @1blustone either way, it is a red herring: if an Integer was received then a nullpointer would not be generated by this call but by the attempt to get the number into the required primitive: long (Long.valueOf(int) doesn't exists) – Rondo Apr 10 '17 at 03:58
  • 6
    There is no such method in Java, you mistook it for `Long.valueOf(long)` – Farid Feb 12 '20 at 03:53
26

If you already have the int typed as an Integer you can do this:

Integer y = 1;
long x = y.longValue();
saret
  • 2,217
  • 13
  • 12
20

use

new Long(your_integer);

or

Long.valueOf(your_integer);
11
 1,new Long(intValue);
 2,Long.valueOf(intValue);
Vikki
  • 1,897
  • 1
  • 17
  • 24
  • For anyone trying now, Long.valueOf(intValue) is the way to go and constructor approach is deprecated. – Nish Jan 02 '23 at 10:01
8

How About

int myInt = 88;

// Will not compile

Long myLong = myInt;

// Compiles, and retains the non-NULL spirit of int. The best cast is no cast at all. Of course, your use case may require Long and possible NULL values. But if the int, or other longs are your only input, and your method can be modified, I would suggest this approach.

long myLong = myInt;

// Compiles, is the most efficient way, and makes it clear that the source value, is and will never be NULL.

Long myLong = (long) myInt;
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
7

In Java you can do:

 int myInt=4;
 Long myLong= new Long(myInt);

in your case it would be:

content.setSequence(new Long(i));
cloudy_weather
  • 2,837
  • 12
  • 38
  • 63
6

I have this little toy, that also deals with non generic interfaces. I'm OK with it throwing a ClassCastException if feed wrong (OK and happy)

public class TypeUtil {
    public static long castToLong(Object o) {
        Number n = (Number) o;
        return n.longValue();
    }
}
Maxim Veksler
  • 29,272
  • 38
  • 131
  • 151
3

We shall get the long value by using Number reference.

public static long toLong(Number number){
    return number.longValue();
}

It works for all number types, here is a test:

public static void testToLong() throws Exception {
    assertEquals(0l, toLong(0));   // an int
    assertEquals(0l, toLong((short)0)); // a short
    assertEquals(0l, toLong(0l)); // a long
    assertEquals(0l, toLong((long) 0)); // another long
    assertEquals(0l, toLong(0.0f));  // a float
    assertEquals(0l, toLong(0.0));  // a double

}
Thamme Gowda
  • 11,249
  • 5
  • 50
  • 57
2

I had a great deal of trouble with this. I just wanted to:

thisBill.IntervalCount = jPaidCountSpinner.getValue();

Where IntervalCount is a Long, and the JSpinner was set to return a Long. Eventually I had to write this function:

    public static final Long getLong(Object obj) throws IllegalArgumentException {
    Long rv;

    if((obj.getClass() == Integer.class) || (obj.getClass() == Long.class) || (obj.getClass() == Double.class)) {
        rv = Long.parseLong(obj.toString());
    }
    else if((obj.getClass() == int.class) || (obj.getClass() == long.class) || (obj.getClass() == double.class)) {
        rv = (Long) obj;
    }
    else if(obj.getClass() == String.class) {
        rv = Long.parseLong(obj.toString());
    }
    else {
        throw new IllegalArgumentException("getLong: type " + obj.getClass() + " = \"" + obj.toString() + "\" unaccounted for");
    }

    return rv;
}

which seems to do the trick. No amount of simple casting, none of the above solutions worked for me. Very frustrating.

  • 1
    if `jPaidCountSpinner.getValue()` returns an Object that is in fact a `Long`, you definitely only need to put a `(Long)` cast in front. Also try putting a breakpoint on your check for `int.class` or `long.class` etc. Does it ever hit it? And if you have a number-like object, it will support `java.util.Number`, so cast it to that and call the `longValue` method. No need to go via a string in that case. So this function could be simplified quite a bit, even if you also need to deal with strings. (Part of the problem here is the bad reference documentation for `JSpinner`). – Daniel Earwicker Oct 24 '11 at 14:27
  • 1
    I too ended up doing something like this. I wasn't sure what kind of number I would receive and was willing to convert it to Long with little concern for efficiency but wanting to avoid boilerplate. – Profiterole Aug 01 '18 at 18:17
2
 //Suppose you have int and you wan to convert it to Long
 int i=78;
 //convert to Long
 Long l=Long.valueOf(i)
Virendra Singh
  • 297
  • 3
  • 9
1

Suggested From Android Studio lint check : Remove Unnecessary boxing : So, unboxing is :

public  static  long  integerToLong (int minute ){
    int delay = minute*1000;
    long diff = (long) delay;
    return  diff ; 
}
Noor Hossain
  • 1,620
  • 1
  • 18
  • 25
1

Apart from the other ways suggested here, one can try the below code as well.

(long)intValue

primitive to primitive.

Shirish Singh
  • 797
  • 7
  • 17
0

As soon as there is only method Long.valueOf(long), cast from int to long will be done implicitly in case of using Long.valueOf(intValue).

The more clear way to do this is

Integer.valueOf(intValue).longValue()
Stanislav Tsepa
  • 710
  • 8
  • 13