I've realized that I really don't understand the difference between if, else and else-if. As I am working through the exercises in my textbook, I seem to apply them more or less interchangeably, and have been lucky so far that no logic error has popped up.
The else-if parts work, but I can't explain to you why.
Quick site searches here and at Stack Overflow didn't turn up a clear and thorough explanation in one place. Can someone point me to a good thread or web page that has some clear examples of when and how to use these two similar but different constructions?
What exactly do you want to know? These keywords in Java mean more or less exactly what they mean in plain English. You could replace the word "else" by "otherwise", I don't know if that helps in understanding it:
Line 3: If the character ch is a letter and inWord is not true
Line 7: Otherwise, if the character ch is a whitespace character
Line 10: Otherwise, if the character ch is a newline
Imagine you are a butler for someone. You are going to show up every day monday through friday to work for them, week after week. They give you a piece of paper that says:
That should be pretty clear.
Note that this COULD be written as a bunch of individual if statements that are independent of each other:
There is a subtle difference between the two ways of writing it. In the first way, ONLY ONE thing will be done. As soon as the first condition that is true is encountered, that block of code runs, and then execution jumps to after the 'else' block. In the second way, each and every case is tested, and it is possible more than one could run. In my second example above, that is unlikely to happen (Unless you start cleaning the office at 11:59 p.m. and then check at 12:01 a.m. to see if it is Tuesday...).
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
The subtle difference Fred mentioned doesn’t show up for days of the week, because they are mutually exclusive. A common example is marks and grades:If you try:… without the elses, only Ds and fails will be recorded properly. If you get 80, then you get an A+, an A, a B, a C and a D all together. Or maybe each if will override the previous one and you will end up with a D for your 80. You could have got that for 40. Hardly seems worth the effort!
Ken Austin wrote:Fred, that is helpful, as well. Thank you. That does make it a lot clearer.
And just to add to what Fred and Campbell have said: this is one area where English and Java (or indeed, any computer language) differ.
In English, we will quite often leave out the 'else's because it's fairly obvious to anyone who's looking at it in written form; but when writing a logical expression, you MUST be explicit about everything.
Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here