What else are permitted extraordinary java method names?

181 Views Asked by At

I know $ can be used as a method name in Java. What else?

class MyClass {
    String $() {
        return "I've never been expected anyone would invoke me";
    }
}

This is actually a practical question. I'm looking for one other than $.

2

There are 2 best solutions below

3
On BEST ANSWER

A method name must be a valid identifier. See Java Language Specification: 3.8 Identifiers for what is a valid identifier.

An identifier must start with a "Java letter" and the rest must consist of characters that are a "Java letter-or-digit".

The JLS says:

The "Java letters" include uppercase and lowercase ASCII Latin letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign ($, or \u0024). The $ sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

The "Java digits" include the ASCII digits 0-9 (\u0030-\u0039).

Letters and digits may be drawn from the entire Unicode character set, which supports most writing scripts in use in the world today, including the large sets for Chinese, Japanese, and Korean. This allows programmers to use identifiers in their programs that are written in their native languages.

Note, in particular, that it says that you should not use $ yourself in your source code (even though it's an allowed character).

1
On

Underscore _ is also a valid character for method name

class MyClass {
    static String _() {
        return "I've never been expected anyone would invoke me";
    }

    public static void main(String[] args) {
        String s =  _();
        System.out.println(s);
    }

}

Output

I've never been expected anyone would invoke me