This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I'm new here and I'm guessing this is a painfully basic question, but I can't find an answer.
I am writing a simple program with several classes, methods, and for loops. For the "counter" variable (not sure if this is the correct term) in the for loop ("int i" in the code below), do I need a new variable name for each for loop? In other words - in which of the examples below can I not (or should I not) use the name "i" for the int variable in the for loop?
As long as you're declaring the loop counter in the loop expression (that's what the for(int i = 0;... bit does) then the scope of that variable is limited to the loop. So if loops don't overlap then you can use the same name. And if they are in different methods there's definitely no problem - variables declared within a method can't interfere with variables in other methods.
But when you've got nested loops you need different names. On your line 10 you should be able to refer to both counters, so you need to be able to tell them apart.
While you're at it - using i for a simple loop counter is usually fine. It's pretty standard usage. But once you start nesting loops it's easy to get the indexes mixed up, so I'd usually suggest trying to give them more meaningful names.