Java Variables

Home / Core Java / Java Variables

Java Variables


Java Variable  

In Java, a variable is a container for storing data that can change during the execution of a program. Variables have a specific data type and a name, allowing you to refer to that stored value by its identifier.

To declare a variable in Java, you specify the data type and the variable name.

Variables in Java have certain rules:

  • Variable names must start with a letter, dollar sign $, or underscore _.
  • They cannot start with a digit but can contain digits after the first character.
  • Variable names are case-sensitive.
  • Java has reserved words that cannot be used as variable names, e.g., int, boolean, String, etc.

The general syntax to declare a variable is as follows:



In Java, variables can be categorized into three main types based on their scope and behavior: local, global (instance), and static variables.


Local Variables

  • Definition: Local variables are declared within a method, constructor, or a block.
  • Scope: They exist only within the block or method where they are declared.
  • Usage: They must be initialized before use and cannot have access modifiers.


Global (Instance) Variables

  • Definition: Global variables, also called instance variables, are declared within a class but outside of any method, constructor, or block.
  • Scope: They are accessible throughout the class and each instance of the class (each object) has its own copy of these variables.
  • Usage: They are initialized with default values if not explicitly initialized and can have access modifiers.


Static Variables

  • Definition: Static variables belong to the class rather than to any instance of the class. They are declared with the static keyword.
  • Scope: They are accessible throughout the class and by all instances of the class. They are initialized with default values if not explicitly initialized.
  • Usage: They can have access modifiers and are shared among all instances of the class.