Variable declarations appearing inside any set of curly braces (a "block") are local to that block. You declared three different variables, all with the same name, each local to the block it's defined in.
Note that you can't just remove the braces: a declaration by itself isn't a legal statement and so can't be the body of a conditional.
What you have to do is declare the variable before the conditional, and then tentatively assign to it:
I'm going to move this to Java in General (Beginner), because it's really unrelated to Servlets. You can follow up there. [ August 01, 2005: Message edited by: Ernest Friedman-Hill ]
Oh, great! Thanks Ernest. I'm not sure how I missed the beginner's forum in the list (though, the list of forums is quite long), but this post definitely belongs here.
Your response makes perfect sense. I'm reading Sun's very own "Core Java 2 - Vol. 1 - Fundamentals", but it never mentions any of the information you just provided (at least nowhere obvious). Makes you wonder who's writing these books and who SHOULD be writing them...
Anyway, thanks a bunch for your help and near-instant reply. You haven't heard the last of me...
author and iconoclast
I second this. I think Core Java is a great book. It was my first book on Java. Of course, I was taking a college course, so I had some help from my instructor to fill in any gaps that I was unsure about. I also had plenty of previous programming experience with C++.
I also agree that Core Java is not a good book for beginners. It seems to be geared towards someone who has programmed in at least one other language before.
Originally posted by Ben Johnson: Oh, great! Thanks Ernest. I'm not sure how I missed the beginner's forum in the list (though, the list of forums is quite long), but this post definitely belongs here.
Your response makes perfect sense. I'm reading Sun's very own "Core Java 2 - Vol. 1 - Fundamentals", but it never mentions any of the information you just provided (at least nowhere obvious)....
For what it's worth, I pulled out my copy of Core Java Volume 1. The authors describe the concept discussed here on page 74 of my edition. This probably isn't helpful since I have an old edition; it is probably on a different page in your edition. The discussion of variable scope is in Chapter 3 "Fundamental Programming Structures in Java" at the beginning of the section titled "Control Flow" under the heading "Block Scope". Since this is a crucial concept, I doubt that they cut it out altogether. I'm willing to bet these headings are very similar, if not exactly the same since this hasn't changed since Java 1.0. In case you are interested, this should describe the same concepts that were explained here from a different point of view. Hopefully it will help solidify the whole idea of variable scope.