Pure Programmer
Blue Matrix


Cluster Map

Variables

Named constants are fine for values that never change during the execution of our programs but we also need to have symbols that represent values that do change as our program runs. Variables are symbols that we set up for such purposes. A variable can not only be initialized to a value when it is created, but can be changed as often as we need. Think of a variable as a box or container that has a name drawn on its side. The name of the variable always stays the same, but what is inside the box can be changed.

Variables Illustration
Variables

Types

In order to declare named constants or variables, we need to specifically declare what type of value they should hold. This idea is known as strong typing. By declaring the types of our symbols, it helps the compiler to detect problems that might arise from mixing different data types. The table below lists the fundamental (or intrinsic) types supported by Java.

Intrinsic Data Types
TypeKeyword
Booleanboolean
Characterchar
8-Bit Integerbyte
16-Bit Integershort
32-Bit Integerint
64-Bit Integerlong
32-Bit Floating Pointfloat
64-Bit Floating Pointdouble
StringString
Voidvoid

Declaration Syntax

Named constants must be initialized to a specific value when they are declared. Once initialized, they can not have their value changed during the execution of the program. The syntax for a variable declaration consists of the type of the variable, the name of the variable (see rules for identifiers), and optionally the equal sign (=) followed by the initializer value for the variable. The declaration ends with a semicolon (;). If no initializer is provided, the variable will have a value of zero (or a zero-like value depending on the type). Examples of statements used to declare variables are illustrated below.

double denominator;
double current_tax_rate = 0.05;
int i = 3;
String errorMsg = "Error 404!";

Variable Declaration Example

Assignment

The thing that separates variables from constants is that we can change their value at any point in the program. This is done with an assignment statement. Assignment statements consiste of the variable name, the equals sign, and a new value for the variable. Examples of statements used to assign new values to a variable are illustrated below.

denominator = 1.2;
current_tax_rate = 0.075;
i = 4;
errorMsg = "Error 403!";

Variable Assignment Example

Questions

  1. Who?
  2. What?
  3. Where?

Projects

More ★'s indicate higher difficulty level.

References