Cooking with Code: Primitive Data Types in Apex and Java

Cooking with Code: Introducing primitive data types in Apex and JavaThinking about variables makes me hungry. That might be taking things a little far, but I’ve been preoccupied with cooking and coding recently, so they seem to be merging in my mind.  I think this stuff can be fun, and for me, silly analogies make it all easier to understand. Hopefully by the end of this post you’ll agree!

My goal today is to provide an overview of primitive data type variables using examples from both Java and Apex. And of course, get some cooking-related metaphors in there while I’m at it.

(Note, so as not to confuse things further, all code below uses Apex syntax.)

Before I talk about variables with primitive data types, it would probably be helpful to talk about what a variable actually is.

What are variables?

You can think about a variable as a container in which stuff can be stored; kind of like those handy kitchen storage containers. They come in different sizes to store different types of things.

blog-oop-primitive-variables4To illustrate this, think about the following scenario:
Showing a kitchen storage container that is storing spaghetti noodles. The container is the variable name, the spaghetti is the value.On Monday night, you cook and use a container to store your leftovers. On Tuesday, once you’ve eaten the leftovers, then you can re-use the container for storing other items.

Variables are similar. They store things. Things otherwise known as values. They can be emptied and you can store another value in them.

So the variable is the container. We put something in it by assigning a value to the variable.
For example, in the following piece of code, I’ve highlighted the variable name in green on the left and the value in blue on the right:
String myContainer = 'Leftovers from Monday';

What we’ve done here is:

  • Create (declare) a variable called myContainer, and
  • Give (assign) it a value of ‘Leftovers from Monday’. We’ve done this using an assignment operator, which is a fancy title for the “=”

Giving something a value, is also called assigning a value or initializing the variable.

containers with different sizes/shapes are like variables with different data typesBut what’s with the bit in orange…what’s that all about?

All variables need to have two things.* The first is a name, e.g., myContainer, and the second is a data type, e.g., in our example myContainer is a variable of the String datatype.

*If they are to be happy and useful variables, then they also need a value, e.g., ‘Leftovers from Monday,’ but technically you can create a new variable without giving it a value.

The data type is always stated before the variable name. The following are all valid ways to create a variable:

String s = 'Women Code Heroes is the best!';
Integer i = 0;
Boolean b;

The last one is tricky, because we have created a variable “b” of the type Boolean, but we haven’t assigned it a value (initialized it). But that’s ok, you can do all of it at once, or you can first declare a variable (create it) and later initialize it (give it a value).

For example, the first two lines of non-comment code are the equivalent of the statement at the beginning of this post (note that comments start with //). For kicks, I’ve added a few more lines…see if you can understand what I’m doing with them.

// We first create the myContainer variable and declare it a String
String myContainer;

// We cook Monday night and fill our container with leftovers
myContainer = ‘Leftovers from Monday’;

// Tuesday rolls around and we eat the leftovers, or in other words,
// we “call a method” called eatContents and point it at our container. Yum!
eatContents(myContainer);

// Wednesday night, we cook again, and store our leftovers
// in our now empty container (Hopefully we cleaned it first! ewwwww!)
myContainer = ‘Leftovers from Wednesday’;

So, what about those data types?

containers with different sizes/shapes are like variables with different data types

In our kitchen storage container analogy, containers come in many shapes and sizes, just right for storing things large (e.g., a baked lasagna), small (e.g., half a lemon), and well…differently shaped (e.g., uncooked spaghetti).

In the same way, we have different variable data types to store different types of … you guessed it … data.

There are simple data types and complex ones, and this post will talk through the simple, or primitive, data types.

What makes a variable data type primitive?

The easiest way I’ve seen to explain what makes a data type “primitive” is to say that it can’t be broken down into a simpler data type component.

cookbook showing that we need 2/3 cups of suger, but don't have a 2/3 cup measure. Instead, we use the 1/3 cup measure twice.One way to think about this is using measuring cups.

If a recipe calls for 2/3 cup of sugar, try as you might, you will not find a 2/3 measuring cup. There isn’t one. Measuring cups are made for the primitive amounts you need for cooking (1/4 cup, 1/3 cup, 1/2 cup and 1 cup).

We don’t need a 2/3 measuring cup, because you would just use the 1/3 measuring cup twice.

What makes a variable data type non-primitive?

Another way to think about primitive data types is to compare them to non-primitive data types (e.g., lists, arrays, sets, collections etc.). A simple example of a non-primitive data type is a muffin baking pan.

We can create a muffinPan variable, which can hold multiple muffins (elements). Because of this we could refer to muffinPan as an array of muffins. Don’t get too hung up on the “array” part just yet, I’ll get into them in a future post; just think of arrays as list or group of things.

muffin tin showing cooked muffins. The pan is non-primitive because it can be broken down into the pan and the muffins.

MuffinPan:

  • First muffin
  • Second muffin
  • Third muffin
  • Forth muffin …

Let’s simplify this and look at our muffin pan and muffins as a bulleted list.

In this written out list, the elements within muffinPan are actually Strings of characters. So we can break a List data type down into its component Strings. But we can’t break down a string into a smaller data type (thankfully there is no character data type).

muffinPan is a list. Lists can be broken down into smaller elements, so are non-primitive data types. The individual muffins are strings, which can't be broken down any further, and therefore are primitive data types.

Another way to say this is we have a List data type that contains four elements of the String data type. So in this way, Lists are non-primitive (can be broken down) and Stings are primitive (can’t be broken down).

There are some other distinctions for what makes a data type non-primitive, but that’s for another post. This is good enough for now. (Phew!)

Examples of primitive data types

kitchen storage containers of different sizes and shapes representing different data types.I’m working with two languages right now (Java and Apex), so I wanted to compare and contrast the different primitive data types for both languages. This is great, because Apex is based on Java, and shares many of the same data types.

There are some exceptions:

  • Some data types exist in Java but not in Apex (e.g., Short), and others are in Apex, but not in Java (e.g., ID).
  • Some of the names for data types (and thus how you declare them) are different in Java than in Apex, e.g., “Int” and “Char” in Java equate to “Integer” and “String” in Apex.

The table below lists the various primitive data types in both Java and Apex, with examples in Apex of how you might declare a variable of that type and assign a value to it. 

Java Apex
Data Type Description Data Type Description Apex Code Examples
Boolean & Character Data Types
Boolean Think of this as a yes/no question. It can store a value of true, false or null1 Boolean true, false or null Boolean b = false;
Char Can store up to 64,435 characters String No set limit String s = ‘Hello women coders of the world!’;
Numerical Data Types without Decimal Points (i.e., whole numbers)
Byte -128 to 127 Integer -2,147,483,648 to 2,147,483,647 Integer i = 5;
Short -32,768 to 32,767
Int -2,147,483,648 to 2,147,483,647
Long a really big negative number to a really big positive number Long a really big negative number to a really big positive number Long negativeReallyBigNumber = -3123476872302339;Long positiveReallyBigNumber = 3123476872302339;
Numerical Data Types with Decimal Points (i.e., fractional numbers)
Float Used in numbers with a decimal point.  Useful when working with fractional numbers but where you don’t need a great degree of precision. Decimal A number that includes a decimal point. Decimal is an arbitrary precision number. In Apex, currency fields are automatically assigned the type Decimal. Also Decimal has a lot of built-in methods and rounding options.2 Decimal dec = 22.2323;
Double Also used when working with number that need to use a decimal point, but more accurate than a float. In Java, use double when working with currency. Double Also a number that includes a decimal point. From a really big negative number to a really big positive number 2 Double dbl = 3.14329;
Apex Specific Data Types
ID A valid 18-character Force.com record identifier ID id=’00300000003S5PGBC0′;
Blob Used to hold files (e.g., images, documents, emails)
Note that Java does not include a date/time primitive data type. Instead you create and use dates through the Date class. See information: http://www.javaworld.com/article/2076270/core-java/calculating-java-dates.html Date Used to indicate a particular day Date todaysDate = Date.today();3todaysDate would output as:2015-01-10 00:00:00Showing date (in years, months and days) and zeros for the time (in hours, minutes and seconds)
DateTime Used to indicate a particular day and time DateTime currentDateTime = DateTime.now();3currentDateTime would output as:
2015-01-10 12:24:42Showing date (in years, months and days) and time (in hours, minutes and seconds)
Time Used to indicate a particular time Time  currentTime = DateTime.now().time();currentTime would output as: 12:24:42:027Showing time in hours, minutes, seconds and milliseconds

1 – Null is actually the absence of a value, which shouldn’t be confused with an empty string or a zero, which represent actual values. I know…fun right?!

2 – I wish I could give a better explanation of when to use Decimal vs Double – the best I can say is if you want to store currency or percentages or need access to more methods and rounding options than are available for Doubles, then use Decimal. Otherwise use Double. I’ll addend this post if I find some better explanation (I’ve got my feelers out).

3 – These examples create dates and times using the built-in methods from the Date and DateTime Apex classes. See more information in Salesforce’s Force.com Apex Code Developer’s Guide

How does all this relate to Salesforce Field Types?

Especially for our Salesforce Awesome Admins who totally rock!  Aalesforce Field Types vs Apex Data TypesSo you can see that we have quite a few basic building blocks to work with here. For those of you Salesforce Awesome Admins, we can equate the Apex data types to field types in Salesforce as follows:

Salesforce Field Type Apex Data Type
Auto-Number String
Checkbox Boolean
Currency By default, assigned as Decimal
Date Date
Date/Time DateTime
Email String
Number Integer or Double, depending on if you set the decimal places to Zero or more than zero when you create the field.
Percent By default, assigned as Decimal
Phone String
Text, Text (Encrypted),Text Area, Text Area (Long), Text Area (Rich) String
URL String

Wrapping things up

There is more I can say about primitive data types, but that’s about all I could possibly hope for anyone to read through. Together, we’ll circle back to this topic in the future when we discuss variables with non-primitive data types, like our pan of muffins example.

For now you know that:

  • Variables are like containers that hold things (values)
  • Variables must, at a minimum, have a name and a data type.
  • Data Types come in two flavors: primitive and non-primitive
  • Primitive data types can’t be broken down into smaller data types (e.g., Strings)
  • Non-primitive data types can be broken down further (e.g., Lists contain elements )
  • Java and Apex have very similar primitive data types

For more information about primitive data types, see Salesforce’s Force.com Apex Code Developer’s Guide.

Hopefully, you enjoyed this food-inspired look at variables with primitive data types. Look for more Intro to Coding blog posts soon.

Can’t wait to see you in the coding kitchen!