3

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
NFE
  • 1,147
  • 1
  • 9
  • 22
  • No; the compiler doesn't _know_ that. – SLaks Jun 04 '13 at 17:27
  • As SLaks says, the compiler has no idea what value will be in `i` at execution (OK, maybe in this case, but not generally), so there's no way to somehow "convert if small enough to fit" without also coercing a "fit" if it's not small enough. For this you use an explicit cast, and pre-check the value if you need to detect an overflow. – Hot Licks Jun 04 '13 at 17:30
  • _An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1._ From Java reference – hamid Jun 04 '13 at 17:35

5 Answers5

5
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");
}
Audrius Meškauskas
  • 20,936
  • 12
  • 75
  • 93
3

Nope, you must do an explicit cast.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • ok thanks but I know that but why this required? can you elaborate. because if value is in range of it then why it is not allow without cast. if we cast then it might lost some info. – NFE Jun 04 '13 at 17:29
  • 1
    Because `i` is a variable that could have any value. If you want to assign `1` to `j`, then you should just assign `1`, but if you're copying it from a variable, it has to allow any `long` value. – Louis Wasserman Jun 04 '13 at 17:30
2

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.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
1

It is not allowed in java. Yes you surely can do it the other way.

dev2d
  • 4,245
  • 3
  • 31
  • 54
0

You should cast it to int:

long i = 1;
int j = (int) i;
Misa Lazovic
  • 2,805
  • 10
  • 32
  • 38