• 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

Compilation error in automatic variable .

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class LocInit {
public static void main(String[] args) {
int weight = 10;
int theprice;
if(weight < 10) theprice = 100;<br /> if(weight > 50) theprice = 5000;
if(weight >= 10) theprice = weight*10;
System.out.println("The price is:" + theprice);
}
}
When i compile the above code iam getting a compilation error as:
LocInit.java:10: Variable theprice may not have been initialized.
System.out.println("The price is:" + theprice);
^
1 error
but the price value is already initialized it in lines 6,7 ,8.Why aim getting a compilation error.
Iam little bit confused about it.Could anybody please help me.

 
Sheriff
Posts: 7001
6
Eclipse IDE Python C++ Debian Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Although you know that that your "if"s are mutually exclusive, the compiler doesn't. It actually shows up an inefficiency in your code too.
The program construct for mutually exclusive cases is "if ... else". This has two benefits: First, teh compiler knows that in every case one and one only of the specified paths will be executed, so it can make assumptions about things like variable initialisations. Second, once one test succeeds, no more tests need be made, so it can be quicker.
I suggest rewriting your tests as:

This should fix your problem.
 
Taylor
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Thanks Thanks Frank
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic