Popular Posts

July 11, 2024

Can we create class name with numbers in Java

 

No, in Java, class names cannot start with a number. According to Java naming conventions and syntax rules:

  • Class names must begin with a letter (A to Z or a to z), currency character ($), or underscore (_).
  • After the first character, class names can include digits (0 to 9), currency characters ($), and underscores (_), in addition to letters (A to Z or a to z).

Valid Class Name Examples

  • Car
  • Account
  • MyClass
  • _Test
  • $ClassName
  • Car123
  • Student_Info

Invalid Class Name Examples

Class names starting with numbers are not allowed:

  • 123Class (Invalid)
  • 5Cars (Invalid)
  • 007Agent (Invalid)

Java Identifier Rules

Java identifiers (which include class names) must adhere to the following rules:

  1. Start Character: Can start with a letter (A-Z or a-z), $, or _.
  2. Subsequent Characters: After the first character, identifiers can include letters (A-Z or a-z), digits (0-9), $, or _.
  3. Keywords: Java keywords (like int, class, public, etc.) cannot be used as identifiers.
  4. Case Sensitivity: Java identifiers are case-sensitive (MyClass is different from myClass).

Example

public class MyClass {
    // Class definition
}

Summary

While Java allows flexibility in naming classes and other identifiers, it strictly enforces rules regarding the starting character of class names. By adhering to these naming conventions, developers ensure that their Java code is both syntactically correct and easy to understand for other programmers.


No comments:
Write comments