Last week, we had the author of TDD for a Shopping Website LiveProject. Friday at 11am Ranch time, Steven Solomon will be hosting a live TDD session just for us. See for the agenda and registration link
hi all when i tried to compile the following code i got an error message saying that the variable y might not have been initialised.I could not understand this since the condition in if will always be true and in that the variable y will be initialised.Can somebody throw some light on this. thanks in advance.
Hi Manish, the compiler can analyse your code to a certain extent but it cannot predict that the value of x is not going to change before that if statement. It does not "run" your code. If, however, you tell the compiler that x is final then the compiler can do a better analysis and the code compiles cleanly.
The compiler wouldn't evaluate the condition in the if clause. So all it sees is that the initialization is done conditionally and thats the reason for the error.
I dont quite agree with Krishna ... If the code is modified to include an else along with the if then it works just fine !
which means that the compiler checks to see if the variable y is initialized or not...In your case...If x were not 5 thn y would never be initialized. So if u have an else clause, it makes sure tht y is initialized all the time. Also if u have something like this..
if(true) y = 0;
then the compiler does not complain.. [ August 10, 2004: Message edited by: Murtuza Akhtari ]
thanks Krishna and Barry. I hav one more query regarding if and while.When i use while(false) i got an error saying Unreachable statement.But if i use if(false) code compiles fine.Why no error in case of if?Please help me. thanx.
Making x final still gives a compilation error. The only thing that might compile this code is using if(true). The compiler knows that the condition is TRUE always, and does not depend on anything else.