Author | Topic: Has anybody had a doubt like this... |
maha anna bartender |
posted March 11, 2000 12:07 PM
We all know that local vars have to be explicitly initialized before they are used. If it is initialized using if..else statement then, it has to be initialized in all branches of the if..else (i.e in the if block and else block) statement. Otherwise if we use only if statement it has to be if(true) statement in order to be sure of the initialization of the local var. In all the above cases the compiler does not complain. It knows at compile time itself, the local var is sure to have an initial val, at run time. In the foll. code the first commented part explains this. But the for the 2nd case , which i have in the foll. code the method checkTrueLiteral(), which supposed to return an int value, if I put only the throw new Exception() , (at any part of the method first/last/middle of the method)the compiler does not complain that the method is not returning an int value. But when I use if(true) throw new Exception() , it wakes up and complains that the method doesn't return an int value. What is bothering me is in effect, if(true) throw new Exception() and just throw new Exception() are all same isn't it?. Otherwise, it shouldn't accept the if(true) localIntVar=100; also right? Doesn't it seem to have a double standard? Can anybody say anything about this? Thank you regds maha anna
[This message has been edited by maha anna (edited March 11, 2000).]
|
Rolf Weasel ranch hand |
posted March 12, 2000 02:23 AM
The rules for definite assignment are laid out in the JLS. These are applicable only to assignment and they are used to verify that method variables are properly initialized before use. The rules cover the if statement situation. As far as non-void methods go, the requirement is that they should never complete normally. Completing normally means reaching the '}' at the end of the method. Hence, return statements cause abnormal completion. So do thrown exceptions. ------------------ [This message has been edited by Rolf Weasel (edited March 12, 2000).]
|
maha anna bartender |
posted March 12, 2000 07:24 AM
Thank you very much Rolf. regds maha anna
|
| | |