permaculture playing cards
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes variable names Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "variable names" Watch "variable names" New topic

variable names

Bill Boyle

Joined: Aug 10, 2003
Posts: 12
Which characters can't a variable name start with? For example is this legal:
int &car = 0;
Do the same rules apply to method names?
Thank you,

Thank you,<br />Bill Boyle
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

According to the Java Language Specification, an identifier (which is a method, class, label, or variable name) can start with "a Java letter." Elsewhere "a Java letter" is defined as basically any Unicode character used as a letter in some alphabet; there's a formal definition in terms of Unicode ranges in the spec (section 20.5.16). The characters "_" (underscore) and "$" (dollar sign) are also considered "Java letters."
There's a method Character.isJavaLetter() which takes a slightly broader view, and I'm actually not sure if the latest version of the spec uses this same definition: according to this method's Javadoc, a Java letter can be not only "$" but any currency symbol, and not only "_" but any "connecting punctuation character."
Anyway, "&" is not legal.

[Jess in Action][AskingGoodQuestions]
Bill Boyle

Joined: Aug 10, 2003
Posts: 12
What about numbers?
Are either of these legal?
int 5num = 10;
int num5 = 10;

O Joseph
Ranch Hand

Joined: Jun 27, 2003
Posts: 75
int 5num=10;
shouldn't compile as the identifier starts with a number. It is "illegal" for an identifier to begin with a number.
int num5=10; //yes this will definitely compile.

Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
To follow up with Ernest's comment about the currency symbol, the following is perfectly legal JavaCode:

\u20A4 is the unicode symbol for the Brtish pound.
[ September 11, 2003: Message edited by: Thomas Paul ]

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
I agree. Here's the link:
subject: variable names
It's not a secret anymore!