Strings
Not Started

As an Apex developer, you'll eventually need to set sObject text fields, define error messages, or keep track of important words and phrases.

To do that, you'll need to use Strings. A String is a set of characters surrounded by single quotes. You have a lot of flexibility here. We'll use the String datatype to declare some variables below:

String errorMessage = 'Error! Unable to calculate the field Amount...'; String stayMotivated = 'Learning how to code! This is so great!'; String validRandomString = '@#$___%@ #$123234.345345 false'; String numberDeclaredAsString = '5'; // This isn't an Integer, it's a String String booleanDeclaredAsString = 'true'; // This isn't a Boolean, it's a String

One catch here is that Apex uses single quotes to identify the start and end of a String. What happens if you want to declare a String that contains a single quote? Let's try declaring a String with this value I’m learning how to code and see what happens.

String stayMotivated = 'I'm learning how to code'; // This wouldn't work. You can quickly tell by the coloring.

We've created chaos. The single quote in I’m is interpreted as the end of the string, causing a compilation error. To fix this, we'll need to escape the single quote inside the string by adding the escape character \. The escape character tells Apex that we want to treat the preceding single quote as a regular character within the string:

String stayMotivated = 'I\’m learning how to code';

That's exactly what we wanted. If this variable is outputted to the user, it will display as I’m learning how to code. The escape character will not be present in the output.

Strings come with many built-in methods. (We’ll learn about methods later, so don’t worry if that sentence doesn’t make sense). To show you an example of the potential, here is some code that detects if the variable greeting contains the substring morning. The code will return true or false and store the value in containsMorning.

String greeting = 'Good Morning'; Boolean containsMorning = greeting.contains('Morning'); // TRUE!

Again, don’t stress about this - I just wanted to give you a sneak peek of the magic ahead of you in this coding journey!

Challenge

Create a String variable called opportunityStage and set the value to Stage 0 - Doesn't Qualify.