Roger Wolfenden wrote:
The tutorials regularly declare variables as having null values before they get used such as String name="";
"" isn't a null value. It's the empty String. Very different from null.
There are a couple different scenarios:
1. Initializing member variables to their default values:
This is pointless, and can lead to unexpected behavior depending on how you write your constructors.
2. Initializing member variables to other than their default values:
This makes sense when you are able to declare and initialize in one shot, without needing extra work first, and if you're going to use the same value regardless fo which constructor gets invoked.
3. Initializing local variables at declaration.
Don't do this unless that value actually means something worthwhile in your method, and you might actually use that value, such as initializing a counter to 0, or initializing a success boolean to false, etc. Don't do it blindly just to make the compiler happy. That's a good way to turn an easy-to-spot compile-time error into a hard-to-debug runtime problem. For instance, in this case, I forgot the case where x = 0 (which could have been handled with a plain old "else"). If I hadn't initialized result, the compiler would have complained that it might not be set when I try to return it. The compiler error would have made me look more closely at my code, and I'd have found my logic error. Now, though, I'll sometimes have my method returning 1 and I won't know why.