What is the meaning of $ in a variable name?
$
is used internally by the compiler to decorate certain names. Wikipedia gives the following example:
public class foo {
class bar {
public int x;
}
public void zark () {
Object f = new Object () {
public String toString() {
return "hello";
}
};
}
}
Compiling this program will produce three .class files:
-
foo.class
, containing the main (outer) classfoo
-
foo$bar.class
, containing the named inner classfoo.bar
-
foo$1.class
, containing the anonymous inner class (local to methodfoo.zark
)
All of these class names are valid (as $
symbols are permitted in the JVM specification).
In a similar vein, javac
uses $
in some automatically-generated variable names: for example, this$0
et al are used for the implicit this
references from the inner classes to their outer classes.
Finally, the JLS recommends the following:
The
$
character should be used only in mechanically generated source code or, rarely, to access preexisting names on legacy systems.
There is no special meaning for a $
in a variable’s name.
While technically allowed, starting the variable name with a dollar sign goes against convention, generally used only by code-generators.
To quote the Java Tutorial by Oracle:
Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.