| Author |
properly initialized
|
Albertina Gonzalez
Greenhorn
Joined: Apr 23, 2002
Posts: 11
|
|
Look the code public class a { public static void main(String args[]) { int x = 10, y; if(x<10) y = 1; if(x>= 10) y = 2; System.out.println("El valor de y es" + y); }} I dont understand why there is compile error, if x = 10 and come in the second if and y is initialized with 2 Why don�t recognized y = 2???
|
 |
Anthony Villanueva
Ranch Hand
Joined: Mar 22, 2002
Posts: 1055
|
|
The compiler is stupid, basically. It will not realize that all possibilities ensure that y will be initialized. However, if you replace the second if with an else, the program will compile and run. Just to be on the safe side, make it a habit of initializing all local variables at the onset.
|
 |
Chad McGowan
Ranch Hand
Joined: May 10, 2001
Posts: 265
|
|
the compiler is ensuring that y is initialized. Since the value of x could change, there is no guarantee(to the compiler) that y is initialized. If you initialize y = 0, this will compile and run. Line 1 in main() int x = 10, y = 0;
|
 |
Albertina Gonzalez
Greenhorn
Joined: Apr 23, 2002
Posts: 11
|
|
Thanks, that sounds trip cuestion. I know, is the best way to make it a habit of initializing all local variables at the onset. But the exam have trip/traps Thank you very much
|
 |
 |
|
|
subject: properly initialized
|
|
|