Skip Top Navigation Bar

Declaring and Initializing Variables

There are two parts to declaring and initializing a local variable.

  • specify the type and then name your variable
  • provide the variable with an initial value

Assignmnet Operator

We use the assignment operator, =, to assign a value to a variable. The format that we follow is as follows:

type variableName = value;

All statements end in a ;.

Examples of Primitive Variables

Description Creation of Variable
Vending Machine Price double itemPrice = 1.99;
Current Game Score int yourScore = 0;
Direction of a Robot int direction = 90;
Last Name Initial char intial = 'S';
Whether a System is Ready or Not boolean isSystemReady = true;
  • Boolean variables can be assigned true or false. The words true and false are Java keywords.
  • Character variables are assigned a character literal. A literal is a fixed value. A character literal is enclosed in single quotes. For following are examples of character literals: '7', 'A', 'b', '-'.

Your Turn

Let's try this out in the Java Playground.

Declare and initialize additional variables:

  • Your middle initial
  • The number of siblings you have
  • Whether or not your are a freshman
  • The weight of a piece of fruit

Modify the code above to declare and initialize other variables.

A Little About Storage

For primitive data (int, double, char, boolean), the value is stored in memory and the location is named with the variable name. For non-primitive data, the data is stored in memory and either this location is named with the variable name or the variable name could contain a reference to the storage location where the data is being stored.

Resources

Next Learn Tutorial

Learn: Declaring String Variables