[OCP 21 book] | [OCP 17 book] | [OCP 11 book] | [OCA 8 book] [OCP 8 book] [Practice tests book] [Blog] [JavaRanch FAQ] [How To Ask Questions] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Abhishek KumarSoni wrote:
Can anyone please explain me why linr number 7 requires a cast.I know whenever you assign a long variable to an int variable an explicit casr is required.But here our long variable l is a final variable and thus compiler knows its value at compile time and it is 90 which is not going to change further in program and 90 can be easily placed in an int container.So why compiler is complaining and giving a compile time error?
Enthuware - Best Mock Exams and Questions for Oracle Java Certifications
Quality Guaranteed - Pass or Full Refund!
Paul Anilprem wrote:
Abhishek KumarSoni wrote:
Can anyone please explain me why linr number 7 requires a cast.I know whenever you assign a long variable to an int variable an explicit casr is required.But here our long variable l is a final variable and thus compiler knows its value at compile time and it is 90 which is not going to change further in program and 90 can be easily placed in an int container.So why compiler is complaining and giving a compile time error?
Because the language designers did not make it acceptable. As per Section 5.2 of JLS, such implicit narrowing can happen only if the expression is a constant of type byte, short, char, or int and the type of the variable is byte, short, or char.
So, no long. Even if it is a constant (in which case the compiler does know its value)![]()
If you want to have fun, try the following code:
mohammad jordan wrote:unreachable statement. because the instance variable (l) marked final so you can not reassign new value OK !!
in while statement the expression (l<10) is false and never change it to true so the cod inner while does not execute never .
but if you initialization any number less than (10) the code will be execute .
Abhishek KumarSoni wrote:
It is ok and I also understand that compilation is fail due to unreachable statement but my question is here compiler knows it very well that long is final and can never be less than 10 its ok and expected behaviour
Abhishek KumarSoni wrote:
but if i write
Here why I can not assign a final long variable l which is 90 to an int container without an explicit cast. 90 is within int range and it is final and it can be placed in int container without any loss then why compiler not allow this.
Consider Paul's rocket mass heater. |