Java underscore

I do not know if this is a duplicate (could not find the words to search, for example, "valid java character"). I had this question in a test interview:

<h / "> Consider the following class:

class _ {_ f; _(){}_(_ f){_ t = f; f = t;}_(_ f, _ g){}}
  • Will it compile?
  • If so, what does this code do?

So my answer was no, but I was wrong. Can someone explain to me how this compiles? (I'm trying to execute my IDE, and I was surprised that yes, it compiles)

+4
source share
4 answers

The underscore is treated exactly like a letter in Java with respect to identifiers. JLS, section 3.8 , covers what an identifier can contain:

- Java Java, Java.

" Java" ASCII AZ (\ u0041-\u005a) az (\ u0061-\u007a), ASCII (_, \u005f) ($, \u0024). $ , , .

, . _, - _, f. 3 - , , f _ f g _, .

t _ f, t f ( f).

+3

Java , , bool, . . . :
http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.8

. :

class SomeClass
{
    SomeClass f;
    SomeClass() {}
    SomeClass(SomeClass f)
    {
        SomeClass t = f;
        f = t;
    }
    SomeClass(SomeClass f, SomeClass g) {}
}
+1

, class _, ( ). , , _ , .

class thing {  //we're declaring a class called 'thing'

thing f;  //the class contains a member variable called 'f' that is of type thing

thing(){  //this is the constructor
}

//It was a default constructor, it doesn't do anything else

//Here is another constructor

thing(thing f) {   //This constructor takes a parameter named 'f' of type thing

// We are declaring a local variable 't' of type thing, and assigning the value of f that was passed in when the constructor was called
thing t = f;  

f = t;  //Now we assign the value of t to f, kind of an odd thing to do but it is valid.
}

//Now we have another constructor
thing(thing f, thing g){  //This one takes two parameters of type thing called 'f' and 'g'
}  //And it doesn't do anything with them...

} //end class declaration

, , java-, .

+1

!

class _ //Underscore is a valid name for a class
{
    _ f; //A reference to another instance of the _ class named f

    _() //The constructor of the _ class
    {
    //It empty!
    }

    _(_ f) //A second constructor that takes an other instance of _ called f as a parameter
    {    
        _ t = f; // A new reference to a _ object called t that now points to f
        f = t;   // f points to t (which, well, points to f :) )
    }

    _(_ f, _ g) //A third constructor with two parameters this time of _ instances.
    {
        //It empty!
    }
} // End of class definition!
+1

All Articles