• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

properly initialized

 
Albertina Gonzalez
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic