String variables in Apex
What is a string?
The String data type is used to represent a sequence of characters, such as text. Any set of characters enclosed in single quotes (' ') is considered a string in apex. It is a primitive data type that can store letters, numbers, and special characters. Strings are commonly used for storing names, addresses, and other text-based information.
How to declare a string?
To declare a string in Apex
- Use the keyword
string. - Follow it with a variable name (choose something meaningful).
- Assign a value using
=and wrap the value in single quotes (' '). - End the line with a semicolon (
;).
String myString = 'Hello, Decodeforce!';In the above example:
The keyword
stringis used to declare a string variable.The variable name
myStringis used to name the string.The value
'Hello, Decodeforce!'is assigned to the variablemyString.
Explore different ways to declare strings
Basic Declaration
Hello WorldString greeting = 'Hello World';Simple string declaration with direct value assignment
Note
The default value for a string in apex is null. Always initialize your string variables before performing any operations to avoid null pointer exceptions.