Variables and Types
Giving your data a name and a shape
A variable is a labeled box for storing a piece of information that your program can use later. Once you give something a name, you can refer back to it again and again instead of retyping the value every time.
Java is what is called a statically typed language, which means every variable must be given a type when you create it. The type tells Java what kind of information the box is allowed to hold, such as a whole number, a decimal number, or a piece of text.
Some common types you will use constantly
intfor whole numbers, like 7 or -42doublefor numbers with a decimal point, like 3.14booleanfor true or false valuescharfor a single character, like 'a'Stringfor text made of many characters, like "hello"
Here is how you create, or declare, a few variables:
int age = 16;
double price = 9.99;
boolean isSunny = true;
String name = "Maria";
On the left is the type, in the middle is the name you chose, and on the right, after the equals sign, is the value being stored. That equals sign is called the assignment operator, and it means store this value in that box.
Variable names in Java usually start with a lowercase letter and cannot contain spaces. If a name needs multiple words, the common style is to capitalize each word after the first, like firstName or totalScore.
You can also change the value stored in a variable later, as long as the new value matches the variable's type:
int score = 10;
score = 25;
Variables are the foundation of nearly everything else you will learn in Java, so it is worth getting comfortable with declaring and using them before moving on.
Quick check
Q1 What must every Java variable be given when it is created?
Q2 Which type would you use to store a true or false value?
Want to save your progress? It's free.
Create a free account