0

I know this question is simple but I could not find an answer anywhere. If I had a method like this:

public long getValue()
{
    int test = 1;
    return test;
}

Would this cause any issues. The code compiles and runs just fine. Do I need to cast (long) on the int before returning it?

  • 3
    You (effectively) already are. [JLS-5.1.2. Widening Primitive Conversion](https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.2) – Elliott Frisch May 25 '19 at 18:45
  • Thank you so much for the short yet highly informative answer. Can you put it in answer so I accept it? @Elliott Frisch –  May 25 '19 at 18:50

2 Answers2

0

long can hold bigger number than int (big int, as it is called in sql).
Int has a minimum value of -2^31 and a maximum value of 2^31-1, while long has a minimum value of -2^63 and a maximum value of 2^63-1, read more here !
If you know that your test value will not pass the limit of int, there will not be any problem, but I'd suggest to return int if you can predict it's size, or both values as long if you are not sure.

amarildo.xyz
  • 932
  • 1
  • 13
  • 21
-1

No, you don't have cast it. Next time compile and run this code.