• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

not compiling

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic