Is the use of one-letter variables encouraged in Java? In code snippets or tutorials, you often see them. I cannot imagine using them is encouraged because it makes the code relatively harder to read and I never see them being used in other programming languages!
-
3Related reading: **[What factors should I consider when choosing names for identifiers?](http://programmers.stackexchange.com/q/134643/22815)** – May 29 '15 at 14:14
-
possible duplicate of [Why are cryptic short identifiers still so common in low-level programming?](http://programmers.stackexchange.com/questions/162698/why-are-cryptic-short-identifiers-still-so-common-in-low-level-programming) – gnat May 29 '15 at 14:58
-
@gnat: that is not even close beeing a duplicate. – Doc Brown May 29 '15 at 16:29
-
2see also: [Why do most of us use 'i' as a loop counter variable?](http://programmers.stackexchange.com/questions/86904/why-do-most-of-us-use-i-as-a-loop-counter-variable) and [Using single characters for variable names in loops/exceptions](http://programmers.stackexchange.com/questions/71710/using-single-characters-for-variable-names-in-loops-exceptions) – gnat May 29 '15 at 16:42
-
@DocBrown per my reading, [top voted answer](http://programmers.stackexchange.com/a/183578/31260) there provides a fairly general explanation of when and why short identifiers are to be preferred – gnat May 29 '15 at 17:16
-
1Does not always make code harder to read. As for example, when you are implementing code based on mathematical equations, it usually makes sense to use the same variable names as used in the equations. (Comments point back to the paper/text where the original equations are to be found, or if you're like me, you sometimes include the LaTeX code for them.) – jamesqf May 29 '15 at 17:42
-
@gnat: that question as well as the top voted are focused on "low level languages". This question here as well as the top answers have a completely different focus. – Doc Brown May 29 '15 at 18:24
-
@DocBrown as I wrote I find the reasoning there general enough to apply here. "Words that are used very frequently, like it, a, but, you, and and are very short, while words that are used less often like observe, comprehension, and verbosity are longer. This observed relationship between frequency and length is called Zipf's Law." – gnat May 29 '15 at 18:27
4 Answers
Properly naming things is hard. Very hard. If you look at it the other way, you can also take this to mean that properly named things are important. (Otherwise, why would you have spent the effort naming it?)
But, sometimes, the names of things just aren't important. That's why we have stuff like anonymous functions ("lambdas"), for example: because sometimes it just isn't worth it naming stuff.
There are a lot of examples, where single letter (or very short) variable names are appropriate:
i
,j
,k
,l
for loop indicesk
andv
for the key and value in a mapn
for a number (e.g. inMath.abs(n)
)a
,b
,c
for arbitrary objects (e.g. inmax(a, b)
)e
for the element in a genericfor each
loopf
for the function in a higher-order functionp
for the predicate function in a filterT
,T1
,T2
, … for type variablesE
for type variables representing the element type of a collectionR
for a type variable representing the result type of a functionex
for the exception in acatch
clauseop
for the operation in a map or fold- appending the letter
s
to indicate the plural, i.e. a collection (e.g.ns
for a collection of numbers,xs
andys
for two arbitrary collections of generic objects)
I never see them being used in other programming languages!
They are very common in pretty much every language I know (and likely also in those I don't know.) Haskell, F#, ML, Ruby, Python, Perl, PHP, C#, Java, Scala, Groovy, Boo, Nemerle, D, Go, C++, C, you name it.

- 101,921
- 24
- 218
- 318
-
10-1 Using 1-letter variables names is lazy programming. Sometimes it's okay to be lazy, but if you're getting up to `k` and `l` in loop indices, that's too far _(you shouldn't have that many nested loops to begin with; extract them to functions)_. Personally, I never use more than one 1-letter variable per function, but I shoot for 0. – BlueRaja - Danny Pflughoeft May 29 '15 at 17:58
-
Also, `l` or `len` is used for a length and `arr` for an array (e.g.: `for(var i=0; l=arr.length; i
– Ismael Miguel May 29 '15 at 18:08 -
5@BlueRaja-DannyPflughoeft I prefer to think of it as efficient programming. Jorg could probably expand on when single letters are appropriate, not just where, but to be honest I imagine most programmers draw the line differently. As for the loop indices, I could argue that any code where the indices don't need names with semantic value is simple enough to justify multi-level nesting over unnecessary extraction. They could also be used in separate loops to avoid possible scoping issues that [Nelson brings up](http://programmers.stackexchange.com/questions/285288/#comment587737_285289). – Lilienthal May 29 '15 at 18:25
-
4@Lilienthal: Code should be efficient-to-read, not efficient-to-write. Usually they are the same thing, but not always, as in this case. – BlueRaja - Danny Pflughoeft May 29 '15 at 18:51
-
@BlueRaja-DannyPflughoeft Not in all programs no, but I don't see anything wrong with Jorg's suggestions. As [Killian](http://programmers.stackexchange.com/a/285289/60605) put it: "Anything longer cannot possibly make the semantics any more obvious, but takes much longer to read." But this is probably largely a matter of personal preference and style. – Lilienthal May 31 '15 at 01:09
-
@BlueRaja-DannyPflughoeft All of the examples Jorg brought up are idiomatic. Any experienced programmer knows what they mean, by convention. Breaking convention in these cases is even worse. If you name your index anything other an `i` I have to spend time figuring out why. – Doval Feb 03 '17 at 17:01
-
@Doval I have to disagree(subjective to my opinions and experience), seeing a variable named "i" or "index" or "panelIndex" in a loop that iterates over a collection of panels has the same readability imo. if the loop itself is a long one (the handling of the condition spans over so and so lines of code) I'd even encourage the verbal approach, so when someone gets to the middle of the handling part, he will be able to immediately understand what is going on. – Noobay Dec 02 '18 at 09:32
If your loop does nothing but use a variable for counting
for(int i = 0; i < 10; i++) {
System.out.println("Stop it! I really mean it!!");
}
then yes, this is the best name you could use. Anything longer cannot possibly make the semantics any more obvious, but takes much longer to read.
If the variable is used inside the loop, a meaningful name can be useful.
for(int door = 0; door < 3; door++) {
int reward = gauge(door);
if(reward > max) {
max = reward;
best = door;
}
}
If your variable is used method-wide, its name should be longer; if it's used class-wide, its name had better be totally self-explanatory, otherwise it will almost certainly decrease the clarity of your code.
In short, the bigger the scope of the variable, the longer its name must be.

- 107,706
- 45
- 295
- 310
-
Honestly, I've gotten to the point where I won't use one character variable names, period. I try to use names that spell out the usage, even for counters. I would typically use a variable named `index` when iterating over an array, for example. – Michael May 29 '15 at 14:38
-
15@Michael: In my opinion, Programming Jargon is its own language, it's not English proper. And in that language, `i` is a proper word with a precisely defined meaning, namely "index you don't need to worry too much about". But I guess it's a matter of familiarity. If you read a lot of Haskell, you'll become accustomed to read `m` as *monad*, `f` as *functor*, `x` as *some object*, `xs` as *a list of `x`s* and so on. – Jörg W Mittag May 29 '15 at 14:43
-
2Just a really huge caveat. Single letter variable names are OK only if the language has proper variable scoping. You will obviously ask 'What language does not have proper scoping?'. Well, took me three hours to learn that JavaScript does not scope the variables in a FOR loop. Try it out with a for loop inside a for loop using the same variable name. It'll blow your mind. – Nelson May 29 '15 at 17:24
-
@Nelson: This question, and this answer, are about Java. Obviously different languages can have somewhat different considerations. (JavaScript is not the same language as Java.) – ruakh May 29 '15 at 18:39
-
I am all for single-letter variable names whenever they make the most sense, but I don't agree that `i` is "the best name you could use" for a loop that uses a variable only for counting. In that case, I would rather see `count` used as the variable name: instantly understandable. `for (int count = 0; count < 10; count++)` or `while (count--)`. – Todd Lehman Jun 08 '15 at 22:21
Reading the code in Kilian's answer, I don't think "there is a loop, and there is a variable, and it has type int, and it has a name, and the name is i, and it is initialised to 0, ...". I just think "loop..." where the three dots stand for unimportant details that I don't even think about. In my programmer's mind, that variable doesn't really exist, it is just an artefact that I have to type, like the for (;;) {} that makes it a loop.
Since that variable doesn't even exist in my mind, why would I give it a name, beyond what is absolutely necessary?

- 42,090
- 4
- 59
- 119
-
I should add that in that kind of construct, I'm often tempted to use not even `i`, but `_` for the obviously meaningless variable. But not everyone is familiar with Prolog, and it would probably create more attention than it removes. – Kilian Foth May 29 '15 at 14:48
-
You also need to consider how the variable is used _inside_ the loop, not just in the `for (...)` header. – May 29 '15 at 14:52
-
@KilianFoth: it's also used that way in Haskell, ML, F# and Scala, I believe. And in Ruby, even though `_` is a legal identifier just like any other, there was a recent change that unused local variables named `_` (or starting with `_`) do *not* generate an "unused local variable" warning, even though Ruby normally warns about them. – Jörg W Mittag May 29 '15 at 16:28
If you are referring to the letters i,j,k as indices within a loop, that is a common practice in Java and other programming languages. Though there its probably better to use a for each style loop, such as
for(User user: users) {
doSomethingWithTheUser(user);
}
instead of
for(int i=0; i<users.size(); i++) {
doSomethingWithTheUser(users.get(i));
}
In Java that style of looping was only introduced fairly recently. That may be why you are noticing it more for Java, as looping over the indices used to be the most common way to loop over an array or list.
There are a few other cases where single letters may be appropriate, such as when implementing a mathematical function where single letters such as n, x, or y, may already be common. But in general, no, name your variables something meaningful.

- 101
-
5"In Java that style of looping was only introduced fairly recently" ... as in, a decade ago? ([Java 5 was released in 2004](http://en.wikipedia.org/wiki/Java_%28software_platform%29#History)) – meriton May 29 '15 at 17:57
-
1Yes that's fairly recent. No I'm not old. Shut up. Damn kids get off my lawn. There are still plenty of legacy Java applications out there from pre Java 5. And even more Java programmers who learned the language on Java 1.4 and refuse to update how they do things. And yet even more code samples online that date back to the early 2000's (yes, we did have the Internet back then; we just called it the Web 2.0). – Nick Jun 03 '15 at 21:25