Variable Types
Similar to algebra, a variable holds a value and acts like it is the value. Variables in Java can hold more than just numbers. They can hold text, true/false values called booleans, characters, lists of multiple values, and more. There are two main categories of variables in java: primitive and reference.
Primitive values are stored directly inside of the variable in a location called the stack. The four main primitive types are:
int- whole numberdouble- non-whole numberchar- a single characterboolean- true or false
(Notice that the names are not capitalized)
Reference values are stored in the heap and not directly in the variable. Instead, the variable contains an address that points to where the actual value is stored. Strings (sequences of characters) and arrays (list of values) are both reference types.
Creating Variables
To declare a variable, first write what type it is. Then, give it a descriptive name. Names must start with a letter and cannot contain spaces.
int teamNumber;
To assign a value to the variable, use the equals sign:
teamNumber = 2240;
Declaration and assignment can be combined into one statement:
int teamNumber = 2240;
If you know that the value stored in the variable will never change, you can declare it by writing final before the rest of the declaration:
final int TEAM_NUMBER = 2240;
TEAM_NUMBER = 0; <- This would result in an error
Now, when you try to assign the variable more than once, it results in an error. This is helpful for enforcing that the value never changes, even if you have forgotten that it shouldn’t be changed.
When naming variables, use camelCase, where the first word is all lowercase and subsequent words have their first letter capitalized. If the variable is final, use SCREAMING_SNAKE_CASE, where all letters are capitalized and underscores are used instead of spaces.
In summary, the blueprint for declaring and assigning variables is as follows:
<type> <name> = <value>;
<name> = <new value>;
Using Variables
To use a variable, just type it’s name as a placeholder for its value:
System.out.println("Brute Force"); <- Prints "Brute Force"
String name = "Brute Force";
System.out.println(name); <- Also prints "Brute Force"