Java - underscore

java

Solution

The underscore character is treated just like a letter in Java, as far as identifiers are concerned. The JLS, Section 3.8 covers what an identifier can consist of:

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter.

and

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 $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

So this compiles. It defines a class called `_`, with a member variable of the same class name `_` called `f`. There are 3 constructors -- one with no arguments that does nothing, one with one `f` argument of type `_`, and one with two arguments `f` and `g` of type `_` that does nothing.

That second constructor declares a local variable `t` of type `_` and assigns the parameter `f` to it, then assigns `t` back to `f` (it doesn't touch the instance variable `f`).

Problem

Don't know if it's a duplicate (couldn't find the words to search like "java character allowed"). I had this question on test interview : Consider the following class : ``` class _ {_ f; _(){}_(_ f){_ t = f; f = t;}_(_ f, _ g){}} ``` - Does this compile ? - If yes, what does this code do ? So my answer was no, but I had wrong. Could someone explain me how does this compile ? (I try on my IDE and I was surprise that yes its compiles fine)

Original source