Search this site

 Java for beginners (topic index)  Variables  for (loops)  if  else  logical operators  arrays  objects

Java variable names

In our introduction to variables, we gave an example of how to name a variable. We mentioned that a name should clearly indicate what the variable represents. But there a few restrictions on variable names and, more importantly, there are various conventions.

There aren't in fact so many restrictions on variable names. But a key one is that they cannot contain spaces; another is that they cannot start with a number. There are also restrictions on what symbols can be used in variable names. But in general, if you don't try and put silly characters and symbols in your variable names (you really don't need to...), then you won't need to worry about what is and isn't allowed.

Beyond the actual restrictions, as mentioned, it's common to apply some variable name conventions so that you end up using a name in a format that programmers are generally used to reading. In general:

  • always start the name with a lower case letter (the first character has to be a letter);
  • omit the and a (and usually of if the meaning is clear);
  • capitalise the first letter of every word that your variable name is made up of (as in our example)— except that you should NEVER capitalise the first letter of the variable name in Java;
  • don't use accented characters or other "silly" characters such as the yen symbol in variable names, even though strictly speaking you may be allowed to (this can just cause problems with character encoding and/or when your colleague isn't used to typing accents);
  • use a couple of common abbreviations:
    • no = number
    • ix = index
  • don't put underscores between the words making up your variable name— there are certain types of variable where this is the convention, but for general variables, it's not the convention.
comments powered by Disqus

Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved.