[java] 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.

This question is related to java casting int long-integer

The answer is


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

}

In Java you can do:

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

in your case it would be:

content.setSequence(new Long(i));

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()

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 ; 
}

 //Suppose you have int and you wan to convert it to Long
 int i=78;
 //convert to Long
 Long l=Long.valueOf(i)

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.


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;

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();
    }
}

use

new Long(your_integer);

or

Long.valueOf(your_integer);

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


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

Integer y = 1;
long x = y.longValue();

 1,new Long(intValue);
 2,Long.valueOf(intValue);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift

Examples related to long-integer

"OverflowError: Python int too large to convert to C long" on windows but not mac How to check a Long for null in java What is the difference between "long", "long long", "long int", and "long long int" in C++? java.math.BigInteger cannot be cast to java.lang.Long A long bigger than Long.MAX_VALUE Definition of int64_t How to convert string to long Convert python long/int to fixed size byte array Converting Long to Date in Java returns 1970 Division of integers in Java