• Post Reply Bookmark Topic Watch Topic
  • New Topic

why should we initialize coin variable at the time of declaration?  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


when i execute this simple program without initializing coin variable it shows variable coin might not have been initialized,,but when i assign a value to coin ..it works well.

plzz direct me to concept behind it..cheers

class money{
public static void main(String args[ ]){
int coin;
int i;
for(i=0;i<11;i++)
{
coin=i;
}
System.out.println(+coin);
}
}
 
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the compiler is not smart enough to figure out that coin will - eventually - get initialized.
 
Marshal
Posts: 56610
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is difficult to program compilers to do that sort of thing. The compiler does not store the value of i and it therefore does not make the assertion that the loop will definitely be entered. It therefore has to assume there is a risk of coin not being initialised.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!