Primitive Data Types and Typecasting

Introduction

Apex is a strongly typed programming language. Data type of variable are explicitly define and enforced. It is a case-insensitive language to avoid confusion with SOQL and SOSL queries as they are case-insensitive. There are 12 primitive data types in apex. As follows: Blob, Boolean, Date, DateTime, Double, Decimal, Integer, ID, Object, Long, String, Time.

Primitive Data Types

Blob

Blob is a collection of binary data store as a single object. It is use to store image, audio files, documents in database. The body of attachment is of type Blob (base64).

String str = 'My Salesforce Stories';
Blob b = Blob.valueOf(str);
System.debug(b);
System.debug(b.toString());
 USER_DEBUG [3]|DEBUG|Blob[21]
 USER_DEBUG [4]|DEBUG|My Salesforce Stories

Boolean

Boolean represents true, false and null values. If Boolean variable is declared and not initialized then, it holds null value. Boolean variables generally use in conditional statements. Resultant of logical, comparison and equality operations are in Boolean.

Boolean b;
System.debug(b);

Boolean a = true;
System.debug(a);

System.debug(a == b);
USER_DEBUG [2]|DEBUG|null
USER_DEBUG [5]|DEBUG|true
USER_DEBUG [7]|DEBUG|false

Please note that in apex compatible data types are only comparable. Otherwise it will throw a runtime exception Comparison arguments must be compatible types

//Explicit type conversion needed.
String str = '9';
Integer i = 9;
System.debug(str == i); //Exception: Comparison arguments must be compatible types: String, Integer

//Type conversion done implicitly.
Integer intValue = 42;
Decimal decimalValue = 42.0;
System.debug(intValue == decimalValue);//true

Date

Date datatype is used to store and manipulate date related information without time component in it. Date values can be created using Date.newInstance(year, month, day). Arithmetic operation on two or more date variables are not allowed. It will throw runtime exception Date expressions must use Integer or Long . Use String.valueOf(date) method to remove appended time component.

Date dt = Date.today();
System.debug(dt);

Date dt1 = Date.newInstance(2022,12,01);
System.debug(dt1);

System.debug(String.valueOf(dt1));

System.debug(dt + 6);
System.debug(dt + dt1.month());//If number of days exceed max no of days in month it automatically overflows.

System.debug(dt.format()); //format method return date as a string according to locale of user.
System.debug(Date.parse(dt.format())); //parse method accept date as a string argument

System.debug(dt + dt1); //Exception : Date expressions must use Integer or Long
USER_DEBUG [2]|DEBUG|2024-02-20 00:00:00
USER_DEBUG [5]|DEBUG|2022-12-01 00:00:00
USER_DEBUG [7]|DEBUG|2022-12-01
USER_DEBUG [8]|DEBUG|2024-02-26 00:00:00
USER_DEBUG [9]|DEBUG|2024-03-03 00:00:00
USER_DEBUG [11]|DEBUG|20/02/2024
USER_DEBUG [12]|DEBUG|2024-02-20 00:00:00

DateTime

DateTime datatype represent specific point in time. It contains both date and time components in it. DateTime value can be constructed using DateTime.newInstance(year, month, day, hour, minute, second). Arithmetic functions which include two or more datetime values are not allowed. Use DateTime.now() method to get current datetime in GMT calendar.

DateTime dt = DateTime.now(); //get current date and time in GMT
System.debug(dt);

String str = dt.format('MM/dd/yyyy HH:mm a');//format datetime in given format
System.debug(str);

Integer hour = dt.hour(); //return hour component from datetime
System.debug(hour);

Integer minute = dt.minute();//return hour component from datetime
System.debug(minute);

Integer day = dt.day(); //return day component from datetime
System.debug(day);

DateTime tomorr = dt.addDays(1);
System.debug(tomorr);

Boolean check = dt < tomorr;
System.debug(check);
USER_DEBUG [2]|DEBUG|2024-02-25 07:51:51
USER_DEBUG [5]|DEBUG|02/25/2024 13:21 PM
USER_DEBUG [8]|DEBUG|13
USER_DEBUG [11]|DEBUG|21
USER_DEBUG [14]|DEBUG|25
USER_DEBUG [17]|DEBUG|2024-02-26 07:51:51
USER_DEBUG [20]|DEBUG|true

Double

Double is a 64 bit number includes floating point. It stores floating point numbers with high degree of precision.

Double db = Math.PI;
System.debug(db);
System.debug(db.format());//returns string representation of double no.
System.debug(db.intValue());//return integer value by typecasting
System.debug(db.round());//return closest long to double
String str = '1.2e6';
System.debug(Double.valueOf(str));//typecast scientific notation number to real number
String str1 = '2.56e-4';
System.debug(Double.valueOf(str1));//System.debug automatically formats small double in scientific notation
System.debug(Decimal.valueOf(str1));
String str2 = '0.0000000256';
System.debug(Double.valueOf(str1));
USER_DEBUG [2]|DEBUG|3.141592653589793
USER_DEBUG [3]|DEBUG|3.142
USER_DEBUG [4]|DEBUG|3
USER_DEBUG [5]|DEBUG|3
USER_DEBUG [7]|DEBUG|1200000.0
USER_DEBUG [9]|DEBUG|2.56E-4
USER_DEBUG [10]|DEBUG|0.000256
USER_DEBUG [12]|DEBUG|2.56E-8

Decimal

A number contains decimal point. Currency fields are automatically assigned the type of decimal. Two Decimal objects that are numerically equivalent but differ in scale (such as 1.1 and 1.10) generally don’t have the same hashcode. Use caution when such Decimal objects are used in Sets or as Map keys.

Decimal d = -9.2345694;
Decimal absDecimal = d.abs();//returns absolute value of decimal
System.debug(absDecimal);

Double dou = absDecimal.doubleValue();
System.debug(dou);

Decimal dec = 890657.89076;
System.debug(dec.format());//returns string value of decimal based on locale.
//round using HALF_EVEN rounding mode means round towards nearest neighbour
System.debug(dec.round());

System.debug(dec.scale());//return the number of decimal places
//Returns the Decimal scaled to the specified number of decimal places, using half-even rounding, if necessary.
System.debug(dec.setScale(2));
System.debug(dec.setScale(3));
USER_DEBUG [3]|DEBUG|9.2345694
USER_DEBUG [6]|DEBUG|9.2345694
USER_DEBUG [9]|DEBUG|8,90,657.891
USER_DEBUG [11]|DEBUG|890658
USER_DEBUG [13]|DEBUG|5
USER_DEBUG [15]|DEBUG|890657.89
USER_DEBUG [16]|DEBUG|890657.891

Integer

Whole numbers represent using Integer data type. It is a 32 bit signed integer. It can represent both positive and negative integer.

Integer i = 10;
Integer j = -10;
Integer k = null;

System.debug(i);
System.debug(j);
System.debug(k);

System.debug(i.format()); //returns string format integer.
Integer l = Integer.valueOf('56905');
System.debug(l);
USER_DEBUG [5]|DEBUG|10
USER_DEBUG [6]|DEBUG|-10
USER_DEBUG [7]|DEBUG|null
USER_DEBUG [9]|DEBUG|10
USER_DEBUG [11]|DEBUG|56905

Please refer Integer Class for more information.

ID

Id represents unique identifiers for records in salesforce platform. Record Ids are store inside Id data type. 15 character Id is case sensitive commonly used in URLs. 18 character Id is case insensitive used for programming purpose. Invalid Ids throws error at run time.

Account acc = new Account();
acc.name = 'test';
insert acc;
Id accId = acc.Id;
System.debug(acc.Id);
//used to describe information about object record
System.debug(accId.getSobjectType());
//return case sensitive 15 char record Id in string
System.debug(accId.to15());
USER_DEBUG [5]|DEBUG|0012w000027fE5MAAU
USER_DEBUG [7]|DEBUG|Account
USER_DEBUG [9]|DEBUG|0012w000027fE5M

Long

Long represents 64 bit signed integers without decimal points. If you are dealing with numbers that exceed the range of Integer it is advisable to use Long explicitly to avoid potential issues with overflow. Long lng = 896456775467809L; The ‘L’ at the end of the literal is used to explicitly denote that is Long type.

Long lng = 8945602349L;
System.debug(lng.format());

Integer i = lng.intValue();
System.debug(i); //8945602349L is outside the range of Integer hence result is an overflow.

Long lng1 = 9065790L;
Integer j = lng1.intValue();
System.debug(j);

String str = String.valueOf(lng);
System.debug(str);
USER_DEBUG [2]|DEBUG|8,94,56,02,349
USER_DEBUG [5]|DEBUG|355667757
USER_DEBUG [9]|DEBUG|9065790
USER_DEBUG [12]|DEBUG|8945602349

Object

All data types supported by apex derived from Object.

Object obj = [SELECT Id, Name FROM Opportunity LIMIT 1];
System.debug(obj);

List<Opportunity> opp = (List<Opportunity>)obj;
System.debug(opp[0].Name);

Object o = 10;
System.debug(o);

Integer i = (Integer)o;
System.debug(i);
USER_DEBUG [2]|DEBUG|(Opportunity:{Id=0062w00000JzF1UAAV, Name=Edge Emergency Generator})
USER_DEBUG [5]|DEBUG|Edge Emergency Generator
USER_DEBUG [8]|DEBUG|10
USER_DEBUG [11]|DEBUG|10

String

String type is essential for manipulation of textual data. It allows us to store sequence of characters. There is no limit on number of characters store in String variable. But, there is a heap size limit which may hit if string value grow too large.

String str = 'hello world';
System.debug(str.length()); //returns length of string i.e. 11
System.debug(str.capitalize()); //returns current string with first letter change to capital
System.debug(str.contains('lo')); //returns true if substring present in string
System.debug(str.indexOf('wo')); //returns index of 1st occurrence substring if not present returns -1. 
System.debug(String.isNotBlank(str)); //returns true if string is not whitespace, empty or null. 

String str1 = ' hello  world ';
System.debug(str1);
System.debug(str1.normalizeSpace()); //returns string with trailing, leading and repetitive whitespaces removed.

System.debug(str1.trim()); //returns string with trailing and leading whitespaces removed.
USER_DEBUG [2]|DEBUG|11
USER_DEBUG [3]|DEBUG|Hello world
USER_DEBUG [4]|DEBUG|true
USER_DEBUG [5]|DEBUG|6
USER_DEBUG [6]|DEBUG|true
USER_DEBUG [9]|DEBUG| hello  world 
USER_DEBUG [10]|DEBUG|hello world
USER_DEBUG [11]|DEBUG|hello  world

Please refer String Class for list of supported methods.

Time

Time data type represents time component without having date in it.

Time t = Time.newInstance(09,10,2,20);
System.debug(t); //Constructs a time from Integer representations.

System.debug(t.addHours(3)); //add hours to hour component of time.
System.debug(t.addMinutes(20)); //add minutes to minute component of time.
System.debug(t.hour()); //returns hour component of time
System.debug(t.second()); //returns the second component of time
USER_DEBUG [2]|DEBUG|09:10:02.020Z
USER_DEBUG [4]|DEBUG|12:10:02.020Z
USER_DEBUG [5]|DEBUG|09:30:02.020Z
USER_DEBUG [6]|DEBUG|9
USER_DEBUG [7]|DEBUG|2

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *