Open In App

Rules For Variable Declaration in Java

Last Updated : 15 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
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  for new switch
assert package  synchronized default goto
boolean do if private this
break else import public throw
byte enum implements  protected  throws
case double instanceof  return transient
catch extends  int short try
char final interface static void
class finally long strictfp  volatile
const float native super while

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

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads