What would happen when the following is compiled and executed. Select the one correct answer public class compare { public static void main(String args[]) { int X=10,y; if(X<10) y=1;<br /> if(X>=10) y=2; System.out.println("y is "+y); } } a. the program compiles and prints y is 0 when executed b. the program compiles and prints y is 1 when executed c. the program compiles and prints y is 2 when executed d. the program does not compile complaining about y not being initialized e. the program throws a runtime exception ans :d I did the code and the answer is d. But y is given value for all (+ve and -ve) values of X. So why compiler complains? Is there anything that I am missing here? Thanks in advance...
Ravindra Mohan
Ranch Hand
Joined: Mar 16, 2001
Posts: 216
posted
0
Hi Jini,
Instead if you coded something like
Then the compiler does realise that variable "y" will definately be initialised no matter whatever the condition is evaluated in the if block . Hope this clears your doubts. Ravindra Mohan.
[This message has been edited by Ravindra Mohan (edited May 10, 2001).]
Art Metzer
Ranch Hand
Joined: Oct 31, 2000
Posts: 241
posted
0
Hi, Jini. Java is smart to enough to figure out mutual exclusivity in this case:
but not in your case:
Art
Micah Holroyd
Greenhorn
Joined: Jan 22, 2001
Posts: 20
posted
0
If you make the X variable final (see code below), then the compiler knows that X will always be 10 and can figure out that Y will be initialized. In the original code, the compiler can't be absolutely sure of what the value of X will be, so it can't predict whether Y will be initialized or not.
Jini Varghese
Ranch Hand
Joined: Dec 06, 2000
Posts: 58
posted
0
Great...That really helped. Thanks a lot.
Samith Nambiar
Ranch Hand
Joined: Mar 14, 2001
Posts: 147
posted
0
hi micah
i tried to compile your code with the final modifier but it still does give me a compilation error regards Samith.P.Nambiar
Jini Varghese
Ranch Hand
Joined: Dec 06, 2000
Posts: 58
posted
0
The second one, with final modifier still gives error.