Variable Rules

In Java, creating a variable is called declaring a variable. The Java programming language is statically-typed. This means all variables must be created(declared) before you can use them.

Variables are given names. The names of the variables are referred to as identifiers. They are rules and conventions to naming variables.

Identifier Naming Rules

  1. All variable names must begin with a letter of the alphabet, an underscore, or a dollar sign.

    total
    _total
    $count
    

    Avoid starting your variable names with the "$" or "_" characters. While it's technically legal to begin your variable's name with "_", this practice is discouraged.

  2. After the first initial letter, variable names may also contain letters, digits 0 to 9, $ and "_".

    __messages
    number2
    

    Conventions (and common sense) apply to this rule as well. Choose full and meaningful words that describe what the variable is being used for.

  3. No spaces or special characters are allowed. The following are illegal variable names :

    2much
    #hashtag
    @username
    first name
    
  4. The name can be of any length, but don't get carried away.
    thisisaverylongvariablebutitslegal
    
  5. Variable names are case-sensitive. Uppercase characters are distinct from lowercase characters. Using ALL uppercase letters are primarily used to identify constant variables. These are two different variables :
    TOTAL
    total
    
  6. You cannot use a Java keyword (reserved word) for a variable name.

results matching ""

    No results matching ""