Open In App

Rules For Variable Declaration in Java

Last Updated : 15 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Variable in Java is a data container that saves the data values during Java program execution. Every variable is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory location name of the data. A variable is a name given to a memory location. For More On Variables please check Variables in Java.

Syntax: 

data _type variable_name = value;

Rules to Declare a Variable 

  1. A variable name can consist of Capital letters A-Z, lowercase letters a-z digits 0-9, and two special characters such as _ underscore and $ dollar sign.
  2. The first character must not be a digit.
  3. Blank spaces cannot be used in variable names.
  4. Java keywords cannot be used as variable names.
  5. Variable names are case-sensitive.
  6. There is no limit on the length of a variable name but by convention, it should be between 4 to 15 chars.
  7. Variable names always should exist on the left-hand side of assignment operators.

List of Java keywords

abstract continue fornewswitch
assertpackage synchronizeddefaultgoto
booleandoifprivatethis
breakelseimportpublicthrow
byteenumimplements protected throws
casedoubleinstanceof returntransient
catchextends intshorttry
charfinalinterfacestaticvoid
classfinallylongstrictfp volatile
constfloatnativesuperwhile

The table above shows the list of all java keywords that programmers can not use for naming their variables, methods, classes, etc. The keywords const and goto are reserved, but they are not currently used. The words true, false, and null might seem like keywords, but they are actually literals, you cannot use them as identifiers in your programs.

Example

Java
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        // Declaring all the
        // possible combinations of
        // variable format
        int _a = 10;
        int $b = 20;
        int C = 30;
        int c = 40;

        int result = _a + $b + C + c;

        // Displaying O/P
        System.out.println("Result: " + result);
    }
}

Output:

Result: 100

Here are a few valid Java variable name examples:

  • myvar
  • myVar
  • MYVAR
  • _myVar
  • $myVar
  • myVar1
  • myVar_1

Next Article
Article Tags :
Practice Tags :

Similar Reads