I am taking an Introduction to Java course and am running through an exercise posted by my teacher. Below are two steps in the exercise:
STEP 11. Add another string variable to store the output message that will be displayed to
the user (initialize as shown below)
String outputMessage = "Bad or incomplete logic";
By initializing the string in such a manner we set a reminder to ourselves that there
could be a problem with our main if ... else if .. else structure. If out logic is correct
then we should never see this message.
STEP 12. Initialize the toValue variable to NaN
toValue = Double.NaN;
Again initializing the double in such a manner we set a reminder to ourselves that
there could be a problem with our logic. Again, if our logic is correct then we
should never see this value.
I don't understand what it means to "initalize" the variable and why this done. Can anyone explain this is in a clear manner?
If I understand your doubt correctly, you are having problem with understanding of 'initialization' process.
Well, in Java, there are two types of variables:
1) Class/instance variables (actually, those two are again different types)
2) Method variables
Now, class/instance variables get their default value without being initialized. That is, when you saythen, data is initialized to 0 and result is initialized to false (because those are default values for respective primitives). For objects, default value is null.
However, when you declare a variable in a method, you cannot use it without initializing. Thus,causes a compilation error, saying that 'The local variable data may not have been initialized'. Change the declaration toand it would work fine.
Now, I myself haven't got a complete idea about your assignment, but I believe it might be something like this(especially when they say 'if our logic is correct, then we should never see this message'):
1) Initialize a variable with some unwanted value
2) Do some stuff
3) If the stuff is correct, the variable should get some wanted value
4) In the end, check the variable value
5) If the stuff we did is correct, then variable should not contain that unwanted value
If I recall correctly, back in the good old days (I think C worked this way), when you declared a variable, you would get a hunk of memory for it. If you didn't initialize it, you got it set to whatever the bit-pattern in that area of memory happened to be. so, if you just said
you would get just about anything. Often it would be 0, but not necessarily. So, you learned to initialize it so that you always started off the same way.
Basically, you are setting the variable's initial state - which you can only do once as others have said.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors