Win a copy of Microservices Testing (Live Project) this week in the Spring forum!
  • 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
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

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: 6962
2
Eclipse IDE Debian Java
  • 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
reply
    Bookmark Topic Watch Topic
  • New Topic