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) class foo
  • foo$bar.class,
    containing the named inner class foo.bar
  • foo$1.class, containing the
    anonymous inner class (local to method foo.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.

Leave a Comment