According to this Sun Java Tutorials page:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html
a double usually gets a default value of 0.0d when it is declared,
however note the caveat for local variables, which means that local
variables must be initialised before use. Because the variable is
declared inside a method (the main method in this case) it is
considered to be a local variable by the compiler and so it must be
initialised.
If your example were coded slightly differently:
class Average {
static double result;
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
int i;
for (i = 0; i < 5; i++) {
result = result + nums[i];
}
System.out.println("Average is " + result / 5);
}
}
Then it would compile, run and would use the default value 0.0d for
result because it is declared outside of a method. Note you have to
use the static modifier so that 'result' can be accessed from the
static context of main.
Basically, in spite of all this it is good practice to declare and
initialise fields in a program so that you know for certain what their
initial value is and also avoiding any issues with local variable scope.
Regards
Nic
On 29/04/2010, at 3:19 PM, chai war wrote:
class Average {
public static void main(String args[]) {
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5; i++)
result = result + nums[i];
System.out.println("Average is " + result / 5);
}
}
--
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en