So now you know what variables are, and you know how to declare them - but we still don’t know the difference between the datatypes. We’ll use the following lessons to figure that out.
We'll begin with the Integer
datatype, which represents whole numbers. Integers can hold positive whole numbers, negative whole numbers, or zero. They can not hold decimal values like 1.5
or 3.14
.
When you declare a variable with the type Integer, you’re telling the Apex compiler (a special program that runs automatically, turning your human-readable code into machine code) that you intend to assign a whole number to the variable. If you try to assign a non-whole number to an Integer variable, you will receive a compilation error and won't be able to save your Apex file. This is a foundational rule you must abide by when building software.
Integer months = 12; Integer amount = 2000; Integer stage = 10; //Use camelCase to declare variables with multiple words in them Integer numberOfDaysInJanuary = 31; Integer mealsInADay = 3; Integer negativeFive = -5; Integer freezingInCelcius = 0; // These would fail to compile/save, so you can’t do this Integer pi = 3.1415926; // trying to assign a Decimal value to an Integer Integer someVariable = 'some random string of text'; // trying to assign a String to an Integer Integer daysInJanuary = '31'; // trying to assign a String to an Integer
These variables may be reassigned:
Integer importantVariable; //Declaring the variable without an initial value importantVariable = 5; // Assigning to 5 importantVariable = 7; // Re-assigning to 7 importantvariable = 31; // Re-assign to 31
Notice how in the last statement, the casing changed to all lowercase. Apex is case insensitive; it doesn't use capitalization to differentiate between variables. However, a diligent & clean coder will strive to keep the casing consistent.
Since Apex is case insensitive, you're not required to capitalize datatypes. So technically, you could do this:
integer mealsInADay = 3;
I wouldn't recommend doing this. Integers are considered an Object
datatype (which we'll cover in another course), so the first letter should be capitalized.