Variables

Variables are used to store data values that can be used and manipulated throughout the program. Each variable has a type that defines what kind of data it can hold.

Declaring Variables

Variables are declared by specifying their type followed by the variable name.

Where:

  • type refers to the data type of the variable.
  • variableName is the name of the variable you are declaring.
  • value is the initial value assigned to the variable (optional, but common when declaring variables).

Examples of declaring variables

Types of variables

Local Variables

  • Declared inside a method, constructor, or block.
  • Only accessible within that specific method or block.
  • Lifetime: Exists only while the method or block is executing.

Instance Variables

  • Declared outside methods, but inside a class.
  • Belong to an object; each object gets its own copy.
  • Lifetime: Exists as long as the object exists.

Class (Static) Variables

  • Declared with the static keyword inside a class.
  • Belong to the class rather than any specific object.
  • Shared by all objects of the class.