How to use variables

Declare and initialize

A variable declaration gives a type, name, and usually an initial value.

int lessons = 26;
String course = "Java";
System.out.println(course + ": " + lessons);

Update a value

Assign a compatible value later, or use an augmented assignment for a concise update.

int score = 10;
score = 15;
score += 2;
System.out.println(score);

Use final constants

A final variable can be assigned only once. Constant names conventionally use uppercase words separated by underscores.

final double TAX_RATE = 0.16;
double total = 100 * (1 + TAX_RATE);

Choose valid names

  • Begin with a letter, underscore, or dollar sign, but normally begin with a letter.
  • Use lowerCamelCase for local variables.
  • Names are case-sensitive and cannot be Java keywords.