• 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

Initialization Question

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was writing a program that displayed the sum, product, average, smallest and largest values of three integers. In order to get the smallest and largest, I used if statements. The compiler wanted the variables "smallest & largest" in the if statements to be initialized, but it didn't fuss about the variables "average, sum, and product." Why is it that variables in if statements must be initialized, but when performing regular calculations the compiler doesn't care?
 
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
We'd need to see your actual code. This sort of thing is usually because the compiler thinks there is one or more ways through the code which leave the values being tested not set to anything.
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The syntax for if statements is
if (some condition){
do something
}
The brackets create a code block (even if you CAN get away with leaving out the brackets when you only have one statement). If you declare a variable in a code block it is local to the block.
If you declare the variable outside of the block, and defer initializing it until inside the Local block, then the initialization is local to the block.
Well, what happens if you reference it somewhere outside the block... The compiler is worried that at that point it will have to process an uninitialized variable.
This is the same rule that is true for method variables. Just explicitely initialize the int's to zero when you declare them, and then assign the value you want in the code block.
PS: you might want to check out the Math.max(), Math.min(), or the Integer compareTo() methods.
 
reply
    Bookmark Topic Watch Topic
  • New Topic