|Primitive Variable||A type of simple variable that is built into Java.|
|Variable Declaration||Creating a new variable.|
|Variable Assignment||Assigning a value to a variable.|
||An integer variable.||
||A decimal variable.||
||A less precise decimal variable.||
||An integer variable that can hold larger numbers.||
||A true/false value.||
||A character based on the ASCII system (essentially a list of different letters/symbols).||
Primitive variables are essentially basic variables, and includes six main types: int, double, float, long, boolean, and char. Variables in programming work like variables in math, but programming variables can have values different than numbers
(x = 15). Now, they can also equal booleans
(x = false), chars
(x = ‘d’), and much more.
In programming, there are two basic components of creating a new variable, the Variable Declaration and the Variable Assignment. The two components are shown in the diagram below:
In the above example,
int is the type,
x is the variable name, and
27 is the value of
x. Primitive variables are all undercase, so declaring a primitive variable as uppercase (saying
Int instead of
int) throws an error. Variable names should represent their meaning in most cases to make code easier to understand (names such as
score are good examples). These variable names make your code easier to interpret by others when working on group projects.
Additionally, all variable names are case-sensitive (
test does not equal
Test), cannot have spaces, and convention dictates that all names are used with camelCasing. This means that the first word is lowercase, and all following words start with a capital. This format is shown below with the other primitive variables:
int myInteger = 27; double myDouble = 14.56; boolean myBoolean = true; char myChar = ‘A’;
If I reassign my variable value after declaration, the variable changes:
int g = 87; System.out.println(g); // outputs 87 g = 15; System.out.println(g); // outputs 15
The variable declaration and variable assignment are not required to be grouped together. For example, the following declaration is completely valid:
int num; // num has no value num = 5; // num equals 5
Finally, there cannot be a mismatch between the variable declaration and variable assignment, or an error will be produced. For example:
boolean testValue = 50; // ERROR
Primitive variables are used very commonly in programming, and often act as the basis of programs that do very complex tasks. Since they are such an important building block, you must remember all the rules of primitive variables.
1. Primitive variables are NOT built into Java.
2. What does the below code output?
int a = 1000; System.out.println(a); a = 8;
3. Is there an error in the below code?
boolean value = true; System.out.println(Value);
4. What is the error in the below code?
char fifteen = A;
Written by Chris Elliott
Notice any mistakes? Please email us at [email protected] so that we can fix any inaccuracies.