my dog learned polymorphism
The moose likes Beginning Java and the fly likes Naming variables in for loops Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Naming variables in for loops" Watch "Naming variables in for loops" New topic

Naming variables in for loops

J Steele

Joined: Feb 28, 2013
Posts: 13

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?

Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

Hi. Welcome to the Ranch!

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.
J Steele

Joined: Feb 28, 2013
Posts: 13
I agree. Here's the link:
subject: Naming variables in for loops
It's not a secret anymore!