Can you automatically convert long to int if long value is small enough to fit into int?
long i=1;
int j=i; //Error Type mismatch: cannot convert from long to int
Can you automatically convert long to int if long value is small enough to fit into int?
long i=1;
int j=i; //Error Type mismatch: cannot convert from long to int
long i;
if (i =< Integer.MAX_VALUE && i >= Integer.MIN_VALUE) {
int j = (int) i; // No loss of precision
} else {
throw new Exception("Cannot convert "+i+" to int");
}
Nope, you must do an explicit cast.
This is a narrowing conversion that requires an explicit cast.
int j= (int) i;
It requires an explicit cast because it might not be small enough to fit, and you can lose information. It's your responsibility to ensure that the long is small enough to fit.
From the Java language specification:
A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.