Valid identifiers

Can a number serve as an identifier in Java?

December 21, 2001

Q: Is there a reason I cannot use numbers as part of package and import statements? For example, if my domain name is www.7ofHearts.com, and I want to create a package using my domain name, then:

package com.7ofHearts;

does not compile, yet:

package com.\u0055ofHearts;

does compile.

If I have an application that needs to import the above package, neither:

import com.7ofHearts.*;  

nor

import com.\u0055ofHearts.*;

will compile.

Is there a workaround, or are numbers not allowed in packages or import statements?

A: In Java, all identifiers must begin with a letter, an underscore, or a Unicode currency character. Any other symbol, such as a number, is not valid. Furthermore, an identifier cannot have the same spelling as one of Java's reserved words. (For a list of keywords and literals reserved from use as identifiers, see "3.9 Keywords" from the The Java Language Specification.)

In Java an identifier is anything used for the name of a declared entity. So an identifier includes all package, class, method, parameter, and variable names. So in the case of 7ofHearts, you are simply out of luck.

My only suggestion: spell out "7." Try com.sevenofhearts instead of com.7ofhearts.

For more information on identifiers, be sure to check out "3.8 Identifiers" from The Java Language Specification.

Tony Sintes is an independent consultant and founder of First Class Consulting, Inc., a consulting firm that specializes in the bridging of disparate enterprise systems and training. Outside of First Class Consulting, Tony is an active freelance writer as well as author of Sams Teach Yourself Object-Oriented Programming in 21 Days (Sams, 2001; ISBN: 0672321092).

Learn more about this topic

Join the discussion
Be the first to comment on this article. Our Commenting Policies