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!

closed as primarily opinion-based by ratchet freak, Neil, Blrfl, gnat, l0b0 May 29 '15 at 18:37

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise. If this question can be reworded to fit the rules in the help center, please edit the question.

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 indices
  • k and v for the key and value in a map
  • n for a number (e.g. in Math.abs(n))
  • a, b, c for arbitrary objects (e.g. in max(a, b))
  • e for the element in a generic for each loop
  • f for the function in a higher-order function
  • p for the predicate function in a filter
  • T, T1, T2, … for type variables
  • E for type variables representing the element type of a collection
  • R for a type variable representing the result type of a function
  • ex for the exception in a catch clause
  • op 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 and ys 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.

  • 4
    -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<l; i++)). Also, fn may be used instead of f, when you refer to a function. – Ismael Miguel May 29 '15 at 18:08
  • 4
    @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. – Lilienthal May 29 '15 at 18:25
  • 1
    @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 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 1:09

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.

  • 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
  • 13
    @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 xs and so on. – Jörg W Mittag May 29 '15 at 14:43
  • 2
    Just 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 8 '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?

  • 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. – user22815 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.

  • 5
    "In Java that style of looping was only introduced fairly recently" ... as in, a decade ago? (Java 5 was released in 2004) – meriton May 29 '15 at 17:57
  • 1
    Yes 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 3 '15 at 21:25

protected by gnat Feb 3 '17 at 17:35

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.