Youtube Video: Intro to Variables and Data Types
Software transforms data. It converts an input into an output. To do that, we use variables within our programs to keep track of the data we’re referencing and manipulating.
Integer year = 2023;
Oh! Would you look at that? A variable was just born ❤️
Variables have three parts. In the example above, we’ve declared a variable with the datatype
Integer, the name
year, and the value
2023.
Naming is one of the hardest things you’ll do as a developer. And you’ll need to do it a lot. Just like in life, names are descriptive ways to identify things.
When we write code, our version of “things” are called datatypes. This course will focus on key primitive datatypes like Integer
, Decimal
, String
, and Boolean
. We'll explore each of these individually in the upcoming lessons, so don't feel overwhelmed just yet.
Here are a few examples of declaring Booleans, a String, a Decimal, and another Integer.
// Declaring a couple Boolean variables below Boolean codingIsFun = true; Boolean codingShouldBeGateKept = false; // Declaring a String variable below String websiteImLearningOn = 'CampApex'; // Declaring an Integer variable below Integer bankPinCode = 1234; // Declaring a Decimal variable below Decimal pi = 3.14;
We don't always know the value of a variable, so we're not forced to assign a value when we declare a variable. We can always set it later like below
// Declaring a Boolean on the first line, assigning a value on the second Boolean codingIsFun; codingIsFun = true;
Don’t confuse this for not knowing the datatype of the variable. Apex is statically typed, meaning you must define the datatype before using a variable. This would not be allowed:
forgotToSetDatatype = 10; // apex needs to know the datatype. This will cause a compilation error.
Variable assignments can be changed throughout the program. For instance:
// Declaring a Boolean Boolean codingIsFun; /* Setting an initial value is allowed because we declared a variable called codingIsFun with the datatype Boolean above. */ codingIsFun = false; // Updating its value codingIsFun = true;
That’s a ton of info. We’ll dive deeper into each one of these datatypes in the upcoming lessons.
One last thing to remember: in Apex, statements must end with a semicolon ;
. The semicolon is a fundamental part of Apex's syntax. The semicolon marks the point at which one statement concludes and the next one begins. Every statement (with a few exceptions) must end in a semicolon. If you forget it, your code won't be able to compile.