13

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
  • 23,794
  • 27
  • 122
  • 225
kon
  • 3,732
  • 3
  • 26
  • 34
  • 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 OurBigBook.com Apr 04 '15 at 08:19

3 Answers3

14

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
  • 61,078
  • 31
  • 152
  • 193
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
  • 437
  • 5
  • 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
  • 707
  • 1
  • 7
  • 15