By providing final, all we are doing is making it FINAL .. i mean the value can not be changed. Am I right?
In that case,
" // Why this statement is compiling? "
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 35241
7
posted
0
That's what I was trying to explain in the first sentence of my previous post; did that make sense to you?
W. Joe Smith
Ranch Hand
Joined: Feb 10, 2009
Posts: 710
posted
0
Sbt Bhatta wrote:By providing final, all we are doing is making it FINAL .. i mean the value can not be changed. Am I right?
In that case,
" // Why this statement is compiling? "
Exactly. So by saying mm will always be 20 (or 40, or anything that can fit into an int and a byte) it will never be bigger than a byte. Since the compiler knows it will never have an issue with fitting mm into the byte num, it will just execute without throwing an exception.
EDIT: Fixed a typo.
SCJA
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
Sbt Bhatta
Greenhorn
Joined: May 21, 2009
Posts: 9
posted
0
aha ! thank you. Thank you. So in essence, the integer value can not be changed . By implicit casting it downwards, we are essentially changing the value. But the final means we cant change it. Cool
Sbt Bhatta
Greenhorn
Joined: May 21, 2009
Posts: 9
posted
0
So in the above code if num is between -127 to 127, then the code compiles. If it is outside the range, then compiler errors with "loss of precision..."
However even if
we get a compiler error. Even though it is easy to see that 1 can easily fit in byte. So in essence to implicitly fit integer into byte one have to use final. Am I right? Please help.!!
W. Joe Smith
Ranch Hand
Joined: Feb 10, 2009
Posts: 710
posted
0
Sbt Bhatta wrote:
So in the above code if num is between -127 to 127, then the code compiles. If it is outside the range, then compiler errors with "loss of precision..."
However even if
we get a compiler error. Even though it is easy to see that 1 can easily fit in byte. So in essence to implicitly fit integer into byte one have to use final. Am I right? Please help.!!
To get it to implicity cast to a byte from an int it has to be final. If you don't want it final, you could always put in an explicit cast, essentially telling the compiler "Hey, I know this is an int I'm putting in here, and it might be too big, but I know what I'm doing."
we get a compiler error. Even though it is easy to see that 1 can easily fit in byte. So in essence to implicitly fit integer into byte one have to use final. Am I right? Please help.!!
The reason behind that is because of compile time constants versus dynamic variables. A final int's value cannot change and hence the compiler can guarantee that the value of that variable will or will not fit into an int. Try compile time constants of 127 128 129 -127 -128 -129 etc etc and you will see how it works