Is it safe to cast a long to an int in Java?
For some reason, the following code , I get ‘-1’ as anIntVar. And I have checked ‘aLongVar’ is not an -1.
public static final long CONST = 1000 * 62;
long aLongVar
int anIntVar = (int)(aLongVar/ CONST);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, its not safe. Don’t do it. Because, A
Long / longhas 64 bit and can hold much more data than anInteger / inthas 32 bit only. Doing the conversion will result in loss of information.If at all you wish to do it, do like this
Use the
.intValue()to convert theLongvalue to anintvalue.