• Post Reply Bookmark Topic Watch Topic
  • New Topic

not compiling  RSS feed

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why the code below does not compile !


but if i initialize it by int m =2 ; then it compiles and run .
so, does it mean java variables are always needed to be initialized ?
why it could not give any garbage value if i dont initialize it!!
my question is why the above code fails to compile ?
 
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
local variables are not initialized by the compiler. in fact, the compiler complains about them, as you found out.
if it were a member variable of a class, then the compiler will initialize it.
as to why it just doesn't give garbage...
because that was (and is) an ENDLESS source of bugs in C code. my guess is that the Java creators were tired of tracking down bugs for uninitialized variables, and just decided not to let you do it.
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See the difference below:
public class ClassName{
........ // declare here is instance variable, is given a default value
public static void main (String[] args){
........ // declare here is local variable, must be initialized before use
}
public void someMethod(){
........ // declare here is also local variable
}
}

}
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a goal of most modern compilers to catch as many errors as possible at compile time. This saves us lots of time.
javac actually tries to check that all paths to the first use of a local variable's value (e.g. both legs of an if statement) give the variable a value.
For example, this won't compile on javac:
void foo() {
int a = 7;
int b;
if (a == 7) b = 10;
a = b;
}
This will compile:
void foo() {
int a = 7;
int b;
if (a == 7) b = 10;
else b = 20;
a = b;
}
Try it yourself. Another compiler might do better here.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!