This content has been marked as final. Show 5 replies
Why is that I can assign a integer value to a double variable, but cannot assign a double value to an integer variable?
Because an integer value IS a double value but a double value is NOT an integer value.
And once again you don't bother to post information you have about the question you are asking.
How do you know you 'cannot assign a double value to an integer variable'? Did you try it? How did you try it? What code did you use? What was your 'double value'? What format did you use?
If you tried it and it failed why didn't you post the code you used and the exact error message you got so people can SEE what it is you are doing and HOW you are doing it.
You will get much better help if you provide ALL of the information you have about the problem you are asking about.
Don't just say "why can't I do this". Provide the example code and say "I used this code to assign a double value to an integer variable and this is the error message that I got". Then post the exact error message.
Why is that I can assign a integer value to a double variableBecause it's a widening conversion that doesn't lose any information. See JLS #5.1.2.
but cannot assign a double value to an integer variable?Because it's a narrowing conversion that might lose information. You can do it as long as you write an explicit typecast. See JLS #5.1.3.
Aren't double and integer compatible types?No, see above.
Isn't there a concept of truncation in java?Yes, see above.
@rp0428 I don't see what good asking for the code and the error message does, in a fundamental case like this. It doesn't change the answer, and your own answer (is/isn't) wasn't too inspiring.
964980 wrote:The second link IS about truncation, only different terminology is used (narrowing). Don't discard based on keywords, read it and understand it and only THEN draw conclusions.
Thanks for the replies.
The two links don't talk about truncation. Can you please share some link regarding truncation? I searched in google but could not find any good site which talks about truncation.
and if that article is nog clear to you (which is understandable), you are free to google for other articles that cover the same material. A research into typecasting will likely net you all the basic understanding you need.