Data types

Ratings:
(4.6)
Views:3826
Banner-Img
  • Share this blog:

Apex Data types 

In Apex all variables and expressions have a data type they are two types of data types

  • Primitive Data types
  • sObject Types

Primitive Data types

A primitive data type such as an Integer, Double, Long, Date, Date Time, String, ID, or Boolean.

  • All Primitive data types are passed by value, not by reference.
  • All Apex variables, whether they are class member Variables or member variables, are initialized to null. Make sure that we initialize variables to appropriate values before using them.

Ex: Initialize a Boolean Variable to False.

Apex Primitive data types include. Boolean: A value that can only be assigned true, false, or null.

Ex: Boolean is Active=True;

Date: value that indicates a particular day. Date values contain no information about time. Date values must always be created with a system static method.

Ex: Date myDate= Date.new instance(2012, 05 , 28);

O/P: is 2012-05-28 00:00:00

Time and Date Time: 

  • These are data types associated with dates and times along with the Date data type.
  • The time data types store times (hours, minutes, seconds and milliseconds).
  • The Date data types store dates (Year month and day).
  • The Date Time data type stores both dates and times.
  • Each of these classes has a new instance method with which we can construct particular date and time values.

EX: Time mytime= newInstance(18,30,2,20);

O/P: is 18:30:02

  • We can also create dates and times from the current clock.

Date myDatetime = Datetime.now(); Date today= Date.today();

  • The date and time classes also have instance methods for converting from one format to another.

EX: Time t= Datetime.now().time();.

---> Finally we can also manipulate the values by using a range of instance methods.

EX: Date myToday = Date.today(0; Date myNext30 = myToday.addDays(30) We will get something like this as the output. 2012-05-28 00:00:00 2012-06-29 00:00:00 Integer, Long, Double and Decimal: To store numeric values in variables, declare variables with one of the numeric data types. Integer, Long Double and Decimal.

Integer: A 32-bit number that doesn't include a decimal point. Integers have a minimum value of -2, 147,483,648 and a maximum value of 2,147,483,647.

EX:- Interger i=1;

Long: A 64-bit number that doesn't include a decimal point longs have a minimum value of -263 and a maximum value of 263-1;

EX: Long l= 2147483648L;

Double: A 64-bit number that doesn't include a decimal point long has a minimum value of -263 and a maximum value of 263-1;

EX: Long l= 2147483648L;

Decimal: A number that includes a decimal point. A Decimal is an arbitrary precision number. Currency fields are automatically assigned the type decimal.

EX: Decimal dec=19.23;

Note: We can use the value of the static method to cast a string to a numeric type. For example, the following creates an Integer from string ‘10’ and then adds 20 to it.

EX: Integer CountMe= Omteger.Valueof('10') +20;

Null Variables:

If we declare a variable and don't initialize it with a value, it will be null. Null means the absence of a value. We can also assign null to any variable declared with a primitive type. Both of these statements result in a variable set to null;

Boolean x=null;

Decimal d;

String: Strings are set of characters and are enclosed in single quotes. They store text values such as a name or an address.

EX: String myvariable= ' Capital info Solutions';

We can also create strings from the values of other types, such as dates, by using the string static method value of().

EX:- Date myDate= Date today(); *** String mystring= String value of (myDate); The o/p of above example should be today's date 2012-05-29

At TekSlate, we offer resources that help you in learning various IT courses. We avail both written material and demo video tutorials. To gain in-depth knowledge and be on par with  practical experience, then explore Salesforce Online Training

sObject Types

A sObject, can be a generic SObject or be a specific SObjects, such as an Account, Contact, or MYcustom__c.

  • sObjects (short for "Salesforce Objects") are standard or custom objects that store record data in the Force.com database.
  • There is also an SObject data type in Apex that is the Programmatic representation of these SObjects and their data in code.
  • Developers refer to SObjects and their fields by their API names.
EX: Account a= new Account ();
MyCustomObject__c co= new MYCusomobject__c ();
API name of Custom Object.

The following example creates an invoice statement with some initial values for the description__c Fields and assigns it to variables of type Invoice-Statement__c, which is an SObject type also.

EX: Invoice-statment__c inv- new Invoice-statement__c(Description__c= 'Test Invoice', Status__c='pending')

sObject Variables are initialized to null but can be assigned a valid object reference with the new operator.

EX:  Account a = new Account();Account a= new Account (Name='Osmania University'), billingcity= 'Hyderabad'); (Or) Account a= new Account (); a.name='Osmania University'; a.BillingCity= 'Hyderabad';

Accessing SObject Fields: 

SObject fields can be accessed or changed with simple dot notation.

EX: Account a = new Account (); a.Name='Capital Info solutions'; Access the account name field and assign it 'Capital Info solutions'.

System-generated fields, such as Created by or last modified by cannot be modified. If we try, the Apex runtime engine generates an error. Additionally, formula fields and values for other fields that are read-only for the context user cannot be changed.

Ex: Contact c=New Contact(); c.count of __c='4': Formula filed (This statement gives an error)

Accessing SObject Fields Through Relationships: Sobject records represent relationships to other words with two fields an ID and an address that points to a representation of the associated sObject.

EX: The contact sObject has both an AccountID field type ID and an Account field of type accounts that point to the associated sObject record itself.

The ID field can be used to change the account with which the contact is associated, while the Sobject reference field can be used to access data from the account.

The following Apex code shows how an account and contact can be associated with one other, and then how the contact can be used to modify a file on the Account.

EX: Account a=new account (Name ='Osmania University') Insert a;

Inserting the record automatically assigns a value to its ID field

EX: Contact c= new contact (Last name='Anil Reddy') C. Account ID=a.ID The new contact now points to the new account. Insert C;

Anonymous Blocks: 

An anonymous block is Apex code that does not get stored in the metadata, but that can be compiled and executed using the developer console.

*We can use Anonymous Blocks to quickly evaluate Apex on the fly such as in the developer console.

Note: 

  1. Can include user-defined methods and exceptions.
  2. User-defined methods cannot include the keyword "static"
  3. We do not have to manually commit any database changes
  4. Unlike classes and triggers, anonymous blocks execute as the current user and can fail to compile if the code violates the user's object and file level permissions.
  • The developer console is a collection of tools we can use to analyze and troubleshoot applications in the salesforce organization.
  • It’s a separate window composed of a set of related tools that allows us to access source code and review how it executes.
  • Access the developer console by clicking

Your Name ---> Developer console --->Click on "click here to enter Apex code" and give the apex code and Click on the “Execute" button ---> Select the particular Operation ---> Click on "Open Raw Log" button --->  Check the result in the USER-DEBUG statement

EX: 

1. Integer i=10; System debug (i);

2. Integer i=10; Integer J=20; System debug (The sum of two numbers'+ (i+j));

For Concatenating two strings

3. String S1='Anil'; String s2='sateesh'; System. debug (‘names are’(s1+s2));

4. Account a =new Account (); a.name ='Capital Info solutions '; System.debug (a name);

You liked the article?

Like : 0

Vote for difficulty

Current difficulty (Avg): Medium

Recommended Courses

1/15

About Author
Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.


Stay Updated


Get stories of change makers and innovators from the startup ecosystem in your inbox