0

I'm saving my source code from my Java textbook exercises and I realise I have a compilation error whenever I save my file using names like " 2-15.java" along with "public class 2-15" in my source code

is there a way so I can name it starting with a number or it is profited in Java?

  • 1
    should be like this A_2_15.java – raksa Aug 18 '17 at 09:54
  • 1
    ... and see https://stackoverflow.com/questions/1841847/can-i-compile-a-java-file-with-a-different-name-than-the-class – slim Aug 18 '17 at 09:55
  • Classes cannot start with a number; by convention they start with a capital and continue using camel case. Unicode characters are apparently allowed (though I wouldn't advise it). – charles-allen Aug 18 '17 at 09:55
  • It is partially possible, file name can be `2-15.java` but class name must start with `A-Z, a-z, _, $`. – Sunil Kanzar Aug 18 '17 at 10:02
  • @HB Not true. `ÉlloWorld` is a valid class name. And the filename must match the class name. – Michael Aug 18 '17 at 10:10
  • First of all Thank You, Because till this day I though class name must start with `A-Z, a-z, _, $` this much of characters. And sorry @Michael but file name and class name can be different if it is not `public`. – Sunil Kanzar Aug 18 '17 at 10:21
  • Okay, the filename *should* match the class name. There's no reason for them to be different. For example, if you decide to change the access level to public later, you'll need to rename your file. – Michael Aug 18 '17 at 10:29

2 Answers2

1

From the language spec:

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

"Letters":

"Java letters" include uppercase and lowercase ASCII Latin letters A-Z, and a-z, and, for historical reasons, the ASCII underscore (_) and dollar sign ($).

"Digits":

The "Java digits" include the ASCII digits 0-9


Your example fails because the first character is not a "Java letter" and a dash is also not a "Java letter".

Further, the convention for class names is to use UpperCamelCase (also called 'PascalCase'), though this is not strictly required by the language.

Some people would argue you shouldn't use digits at all in class names but I personally disagree with this. It can result in much more readable names than otherwise would be possible. For example: AspectRatio16x9 vs AspectRatioSixteenByNine

Michael
  • 41,989
  • 11
  • 82
  • 128
0

Classes cannot start with the numbers as per naming convention.It has to start with the Capital letter first..

  • Not "as per naming convention". 'Convention' is simply "a way in which something is usually done". In fact, its strictly prohibited by the specification of the language. – Michael Aug 18 '17 at 10:04