Please let me know what is the output of the following code (with explanation...why and how) public class Compare { public static void main(String args[]) { int x = 10, y; if(x < 10) <br /> y = 1;<br /> if(x>= 10) y = 2; System.out.println("y is " + y); } }
Regards, Manish Singhal
Jane Griscti
Ranch Hand
Joined: Aug 30, 2000
Posts: 3141
posted
0
Hi Manish, The code won't compile. 'y' is an instance variable; which are not initialized to any default values. Given the code, we know that 'y' will be initialized at some point but the compiler doesn't; hence the error. Hope that helps.
It won't compile. Variables inside methods have to be initialized before you can use them. You can't initialize them inside if blocks because the compiler doesn't know whether or not that if block will execute. If this was a member variable, outside of the method (it would have to be static also since main is a static method) then it would be initialized to 0 and the code would work and give you "y is 2". Bill
Jon Aryan
Greenhorn
Joined: Oct 06, 2000
Posts: 22
posted
0
Jane ... "y" is a local variable ... not an instance variable ! ... may be a typo rite ?? Aryan.
Manish Singhal
Ranch Hand
Joined: Sep 21, 2000
Posts: 104
posted
0
Thanks to all of you. I knew that we have to initialize local variable before using it but was confused and thought that " if " construct will initialize it. regards, Manish
Stephen Pride
Ranch Hand
Joined: Sep 14, 2000
Posts: 121
posted
0
But ... If the code were this instead:
Then it will compile without any errors. So even though "y" was not initially initialized, the compiler "knows" it will be before it is used. Regards, SP
SCJP
Manish Singhal
Ranch Hand
Joined: Sep 21, 2000
Posts: 104
posted
0
Thanks Stephen regards, Manish
Bin Zhao
Ranch Hand
Joined: Oct 04, 2000
Posts: 73
posted
0
So,the compiler is so smart that it can judge whether y can be initialized.But if in another situation,how can we judge if the compiler can make correct decision?
Jane Griscti
Ranch Hand
Joined: Aug 30, 2000
Posts: 3141
posted
0
Hi John ... You're right ... and I knew that when I posted! Thanks for correcting my mistake ------------------ Jane