user3956566
user3956566

Reputation:

Can the "-" symbol be used in naming?

I have started java at uni, I have my notes on syntax, and have googled. Haven't, yet written a program. I have gone through my notes, googled and cannt find an answer to this.

I can find that the "-" is used as an operator in java. I can see that names are not permitted to start with a number. "_" are allowed.

What I cannot find, is the "-" symbol permitted to be used in naming classes, methods or variables in java?

eg "fat-smelly-cat"

I just want to be sure of the definitive answer

Upvotes: 0

Views: 151

Answers (3)

Saj
Saj

Reputation: 18712

'-' is not valid. The below snippet will give you a 'fascinating' list of characters that you can use-

for (int i = Character.MIN_CODE_POINT; i <= Character.MAX_CODE_POINT; i++){
    if (Character.isJavaIdentifierStart(i) && !Character.isLetter(i)){
        System.out.print((char) i + "\t");
    }
}

If your console cannot print the characters, try changing-

System.out.print((char) i + "\t");

To:

System.out.print(i + "\t");

Then you can see the code and find the character representations online.

Upvotes: 4

LaurentG
LaurentG

Reputation: 11757

No, it is not possible. You will find more information about allowed characters in the Java specification.

Upvotes: 5

assylias
assylias

Reputation: 328618

The JLS #3.8 defines what identifiers are valid: they must start with a "Java Letter" followed by zero or more "Java letter-or-digit". The two sets are defined as follows:

  • A "Java letter" is a character for which the method Character.isJavaIdentifierStart(int) returns true.
  • A "Java letter-or-digit" is a character for which the method Character.isJavaIdentifierPart(int) returns true.

Character.isJavaIdentifierPart('-') returns false, so the answer is no.

Upvotes: 8

Related Questions