Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

Recently, I found that $ is allowed in Java variable names, but has a special meaning. Unfortunately, it isn’t mentioned what this special meaning is.

So, my question is: What is the special meaning of $ in variable names in Java?

Here is the exact quote from 

Java: An Introduction to Problem Solving and Programming

From Walter Savitch:
 

Java does allow the dollar sign symbol $ to appear in an identifier, but these identifiers have a special meaning, so you should not use the $ symbol in your identifiers.

1 Answer

0 votes
by (13.1k points)

$ is used internally by the compiler to decorate certain names.

public class fool {

    class bar {

        public int x;

    }

    public void ozark () {

        Object f = new Object () {

            public String toString() {

                return "hello";

            }

        };

    }

}

Compiling this program will produce three .class files:

fool.class, containing the main class foo

fool$bar.class, containing the named inner class fool.bar

fool$1.class, containing the anonymous inner class

All of these class names are valid

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.

Want to learn Java? Check out the Core Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Feb 25, 2021 in Java by dante07 (13.1k points)

Browse Categories

...