Skip to content

Variables

This content is for Java. Switch to the latest version for up-to-date documentation.

A variable in Java is a named storage location in memory that holds a value which can be changed during program execution. Variables allow you to store, retrieve, and manipulate data in your programs.

  • Has a specific data type (e.g., int, double, String)
  • Has a name (identifier)
  • Can store a value (which may change during program execution)
  • Has a scope (where it can be accessed in the code)
TermDescriptionExample
DeclarationIntroducing a variable’s name and type to the compiler, without necessarily assigning a valueint x;
DefinitionBoth declaring a variable and assigning it an initial valueint x = 10;

The basic way to assign a value is with the assignment operator (=):

// Simple variable declaration and assignment
int age = 25;
double salary = 75000.50;
char grade = 'A';
boolean isActive = true;
String name = "John Smith";

You can assign the result of an expression to a variable:

int a = 5;
int b = 10;
int sum = a + b; // sum equals 15
int product = a * b; // product equals 50
double result = (a + b) / 2.0; // result equals 7.5
  1. Initialize variables when declaring them, unless there’s a specific reason not to
  2. Use meaningful variable names that describe what the variable represents
  3. Limit variable scope to where it’s needed
  4. Use final for values that shouldn’t change
  5. Be careful with type conversions to avoid data loss
Built with passion by Ngineer Lab