A variable is a named location in memory that stores data while a program runs. You declare a variable by stating the data type and the variable name.
int age;
double price;
String name;
A variable must be declared before it is used.
A data type tells Java what kind of data the variable will hold and how much memory it needs. Java is strongly typed, meaning the type cannot change after the variable is declared.
There are two major categories:
Stringint students = 30;
int score = 95;
double temperature = 98.6;
double gpa = 3.75;
boolean isFinished = false;
boolean passed = true;
' '.char grade = 'A';
char symbol = '#';
" ".String name = "Mr. Cusack";
String school = "Klein Collins High School";
int age;
age = 17;
int age = 17;
double price = 4.99;
boolean isReady = true;
char letter = 'C';
String city = "Houston";
_, or $.int studentCount;
boolean isValid;
String firstName;
Variables can be updated after declaration (except final variables).
int score = 80;
score = 90; // updated
| Mistake | What’s wrong |
|---|---|
int x = 3.14; |
Cannot store decimals in an int. |
char letter = "A"; |
Strings use quotes " ", chars use ' '. |
String name = 'Bob'; |
Strings need " ", not ' '. |
boolean done = yes; |
Must be true or false. |
| Data Type | Category | Example | Description |
|---|---|---|---|
| int | Primitive | int age = 16; |
Whole numbers |
| double | Primitive | double temp = 98.6; |
Decimal values |
| boolean | Primitive | boolean flag = true; |
True/false |
| char | Primitive | char letter = 'A'; |
Single character |
| String | Reference | String name = "Joe"; |
Text / words |