The dollar symbol ($) is a valid character to name a variable, e.g. String superSecretFormula$;
, but when we're talking about naming conventions, when should I use this symbol?
Underscore for example is most used to separate words, as blank spaces are not allowed.
Never.
McDowell quoted the JLS, here is an example that fails to compile on Oracle JDK 1.8.0_45:
The problem is that
javac
generates a field$assertionsDisabled
to implementassert
, which conflicts with our field, andjavac
says:See also: https://stackoverflow.com/a/29439538/895245
I agree that, in general, the use of the special symbol $ should be avoided, as explained by Richard. However, I remember seeing the use of $ to define a jQuery-like selector in the reactor project. I think that, used with caution, the $ symbol can help to define some beautiful APIs in Java.
Your question is tagged Java, but it looks like you're asking about type characters, which are still supported in Visual Basic but not widely used these days (nor for a long time).
This is a bit subjective, but I think it's fair to say: never
One scenario where you might want to prefix a variable name with
$
is when writing JavaScript code to distinguish jQuery objects.Edit
Regarding starting a variable name with a
$
, the Oracle Java tutorials tell us:In Java, I use the "_" as a prefix to a private class-wide non-static variable or fields and "$" as a prefix to a private class wide static variable.
Its better than using the "m" prefix because it does not block the line of reading. You obviously would not begin to read the "_" or the "$" when you begin to read the variable word, right? Like _addressMap or $addressMap but with m like in Map mAddressMap it can be confusing at the point you are beginning to read it.
Although it is not conventional Java code, its a great help to mark those variable so you can understand them promptly if they are class-wide or not, or static or non-static. Of course you must discuss this to your teammate at first hand.
From the Java Language Specification on identifiers:
Theoretically you can use dollar sign in variable names, but it's strongly discouraged because that symbol is used internally by the compiler(e.g. inner or anonymous classes's name).
Please refer to two related questions on the stackoverflow: What is the meaning of $ in a variable name? and Java class name containing dollar sign fails to compile if an inner class is present