11

I read about the naming of Java variables. It says that Java variables cannot start with any numbers and special characters except for $ and _.

Some valid examples:

int count;
int _count;
int $count;

And some invalid examples:

int %count;
int 4count;
int #count;

Do the same rules apply to method names?

Stevoisiak
  • 20,148
  • 23
  • 110
  • 201
kon
  • 3,174
  • 3
  • 24
  • 33
  • Is there a reason why you'd want to use characters like these at the start of a variable, method, or anything? – wattostudios Apr 18 '12 at 14:10
  • 1
    I'm working on an extern domain specific language with Xtext that is executed on Java virtual machine. That's why I would like to make this precise :) Thanks! – kon Apr 18 '12 at 14:15
  • 1
    possible duplicate of [Legal identifiers in Java](http://stackoverflow.com/questions/11774099/legal-identifiers-in-java) because of http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4 – Ciro Santilli Путлер Капут 六四事 Apr 04 '15 at 08:19

3 Answers3

13

Yes, method names and variable names are what's called "identifiers". Identifiers all share the same rules regarding accepted characters. Take a look at §3.8 from the Java Language Specification to find out exactly what an identifier may contain, and §6.2 for an explanation about how identifiers are used.

rid
  • 57,636
  • 30
  • 143
  • 185
1

You might be surprised when having unusual characters for method, such as:

public void mój_brzuch_zacznie_burczeć()

and it works pretty nice. Take a look at this blog to see more fancy examples.

Damian
  • 325
  • 4
  • 11
  • or U+02BC (Modifier Letter Apostrophe) `void itʼs_a_method()`. You can use any modifier letters https://unicode-table.com/en/blocks/spacing-modifier-letters/ – Joter Jun 08 '21 at 23:00
0

From the Java Tutorial:

"Although a method name can be any legal identifier, code conventions restrict method names." http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html

Christian
  • 687
  • 1
  • 7
  • 15