Apex introduction Flashcards

1
Q

Apex is a strongly-typed programming language. What is a strongly-typed programming language?

A

Strong vs weak

The opposite of “strongly typed” is “weakly typed”, which means you can work around the type system. C is notoriously weakly typed because any pointer type is convertible to any other pointer type simply by casting. Pascal was intended to be strongly typed, but an oversight in the design (untagged variant records) introduced a loophole into the type system, so technically it is weakly typed. Examples of truly strongly typed languages include CLU, Standard ML, and Haskell. Standard ML has in fact undergone several revisions to remove loopholes in the type system that were discovered after the language was widely deployed.

What’s really going on here?
Overall, it turns out to be not that useful to talk about “strong” and “weak”. Whether a type system has a loophole is less important than the exact number and nature of the loopholes, how likely they are to come up in practice, and what are the consequences of exploiting a loophole. In practice, it’s best to avoid the terms “strong” and “weak” altogether, because

Amateurs often conflate them with “static” and “dynamic”.

Apparently “weak typing” is used by some persons to talk about the relative prevalance or absence of implicit conversions.

Professionals can’t agree on exactly what the terms mean.

Overall you are unlikely to inform or enlighten your audience.

The sad truth is that when it comes to type systems, “strong” and “weak” don’t have a universally agreed on technical meaning. If you want to discuss the relative strength of type systems, it is better to discuss exactly what guarantees are and are not provided. For example, a good question to ask is this: “is every value of a given type (or class) guaranteed to have been created by calling one of that type’s constructors?” In C the answer is no. In CLU, F#, and Haskell it is yes. For C++ I am not sure—I would like to know.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does Anonymous Block allow you to do?

A

Anonymous Blocks
The Developer Console allows you to execute code statements on the fly. You can quickly evaluate the results in the
Logs panel. The code that you execute in the Developer Console is referred to as an anonymous block. Anonymous
blocks run as the current user and can fail to compile if the code violates the user’s object- and field-level permissions.
Note that this not the case for Apex classes and triggers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a class referred to in the coding world?

A

Sometimes

referred to as blueprints or templates for objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Describe what the exact code below is:

public static void sayYou() {
System.debug( ‘You’ );
}

A

A public static method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Describe what the exact code below is:

public void sayMe() {
System.debug( ‘Me’ );
}

A

An instance method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
Write the code that will call the static method below:
public class helloworld(){
public static void sayYou() {
System.debug( 'You' );
}
A

HelloWorld.sayYou();

The class does not need to be instantiated for a static method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
Write the code that will call the static method below:
public class helloworld(){
public void sayMe() {
System.debug( 'Me' );
}
}
A
HelloWorld hw = new HelloWorld();
hw.sayMe();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Describe what the exact code below is:

public static string helloMessage() {
return(‘You say “Goodbye,” I say “Hello”’);
}

A

A public static data type

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is a string in Apex?

A

A primitive data type

Strings are set of characters and are enclosed in single quotes.

They store text values such as a name or an address.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Write a method that does not return any value but will pass a string data type as an argument

A

public static void processString(String s) {
s = ‘Modified value’;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a Boolean?

A

Boolean values hold true or false values and you can use them to test whether a certain condition is true or false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are Time, Date and Datetime?

A

Variables declared with any of these data types hold time, date, or time and date values combined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the four kinds of variables to hold numeric values?

A

Integer
Long
Double
Decimal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is a variable that you don’t assign a value to?

A

Null Variables and Initial Values
If you declare a variable and don’t initialize it with a value, it will be null. In essence, null means the absence of a value.
You can also assign null to any variable declared with a primitive type. For example, both of these statements result in a
variable set to null:

Boolean x = null;
Decimal d;

Many instance methods on the data type will fail if the variable is null. In this example, the second statement generates an
exception (NullPointerException)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is an Enum?

A

An enumeration of constant values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Write the code so that a Date data type has a variable called MyDate and is assigned the value of today. Then write another line of code that will retreive todays date as a string. Write a debug statement to call the string extraction variable and add the text before it “today’s date is “.

A

Date myDate = Date.today();
String myString = String.valueOf(myDate);
System.debug(myString);

2012-03-15

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What will be the output from the debug statement?

String x = 'I am a string';
String y = 'I AM A STRING';
String z = 'Hello!';
System.debug (x == y);
System.debug (x != z);
A

True

True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Apex code is limited by the number of operations
(such as DML or SOQL) that it can perform within one process.
How records can an apex request collection return?

A

All Apex requests return a collection that contains from 1 to 50,000 records

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Why must you bulkify your code

A

Because you cannot assume that your code will be handling one record at a time. Eg a User inserting 1000 contacts

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is Visualforce?

A

Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and customizing the Salesforce user interface.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Provide some examples of what you can do with Visualforce

A
  • Build wizards and other multistep processes.
  • Create your own custom flow control through an application.
  • Define navigation patterns and data-specific rules for optimal, efficient application interaction.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How is Apex compiled, stored, and run entirely on the Force.com platform?

A

When a developer writes and saves Apex code to the platform, the platform application server first compiles the code into an
abstract set of instructions that can be understood by the Apex runtime interpreter, and then saves those instructions as
metadata.
When an end-user triggers the execution of Apex, perhaps by clicking a button or accessing a Visualforce page, the platform
application server retrieves the compiled instructions from the metadata and sends them through the runtime interpreter before
returning the result. The end-user observes no differences in execution time from standard platform requests.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Apex is not a general purpose programming language. What can’t you do with apex?

A

Apex cannot be used to:
• Render elements in the user interface other than error messages
• Change standard functionality—Apex can only prevent the functionality from happening, or add additional functionality
• Create temporary files
• Spawn threads

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Describe what the statement below is doing:

Account[] accs;

A

Declaring a variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Describe what the statement below is doing: for (integer i = 0; i < 9; i++){ }
Incremental Control Structure
26
Describe what the statement below is doing: Contact[] cons = new Contact[0] cons;
Array (list)
27
Describe what the statement below is doing: upsert cons;
DML statement
28
Reserved Apex Keywords A-C *marked are for future use
``` abstract activate* and any* array as asc autonomous* begin* bigdecimal* blob break bulk by byte* case* cast* catch char* class collect* commit const* continue convertcurrency ```
29
Reserved Apex Keywords D-G *marked are for future use
``` decimal default* delete desc do else end* enum exception exit* export* extends false final finally float* for from future global goto* group* ```
30
Reserved Apex Keywords N-P *marked are for future use
``` new next_90_days next_month next_n_days next_week not null nulls number* object* of* on or outer* override package parallel* private protected pragma* public ```
31
Reserved Apex Keywords T-Y *marked are for future use
``` testmethod = declare testmthd then* this throw today = system.today tolabel tomorrow = system.tomorrow?? transaction* trigger = instantiate a trigger true = boolean is true try = exception entry statement type* undelete = trigger is undelete update = trigger is update upsert = trigger is upsert using virtual webservice when while where yesterday ```
32
Reserved Apex Keywords H-M *marked are for future use
``` having* hint* if implements import* inner* insert instanceof interface into* int join* last_90_days last_month last_n_days last_week like limit list this_month* long this_week loop* map merge ```
33
Reserved Apex Keywords R-S *marked are for future use
``` retrieve* return returning* rollback savepoint search* select set short* sort stat* super switch* synchronized* system ```
34
When can you use Apex reserved keywords when naming variables, methods or classes?
You cannot use any of the Apex reserved keywords when naming variables, methods or classes
35
How do you declare a variable?
Variables are declared with a name and a data type. You can assign a value to a variable when you declare it. You can also assign values later. Use the following syntax when declaring variables: datatype variable_name [ = value];
36
Describe what the statement below is doing: Decimal Total;
Declaring a variable that has the data type of Decimal with the name Total. Note: that no value has been assigned to it.
37
Describe what the statement below is doing: Integer Count = 0;
Declaring a variable that has the data type of Integer with the name Count, and has the value of 0.
38
How are arguments treated in Apex for: a) Primitive Data Types b) Non-Primitive Data Types
In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost. Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method returns, the passed-in argument still references the same object as before the method call and can't be changed to point to another object. However, the values of the object's fields can be changed in the method.
39
What is a statement in Apex and programming in general?
A statement is any coded instruction that performs an action.
40
a) What must be at the end of a statement? | b) Name the 8 types of different statements in Apex
a) semicolon ``` b) A statement can be one of the following types: • Assignment, such as assigning a value to a variable • Conditional (if-else) • Loops: ◊ Do-while ◊ While ◊ For • Locking • Data Manipulation Language (DML) • Transaction Control • Method Invoking • Exception Handling ```
41
What are the types of loops you can have?
◊ For ◊ Do-while ◊ While
42
What is a block in Apex?
A block is a series of statements that are grouped together with curly braces and can be used in any place where a single statement would be allowed. For example: ``` if (true) { System.debug(1); System.debug(2); } else { System.debug(3); System.debug(4); } ``` ``` In cases where a block consists of only one statement, the curly braces can be left off. For example: if (true) System.debug(1); else System.debug(2); ```
43
What are the 3 types of collections available?
Apex has the following types of collections: • Lists (arrays) • Maps • Sets
44
What elements can you contain in a list?
A list is a collection of elements, such as Integers, Strings, objects, or other collections
45
When should you use a list?
Use a list when the sequence of elements | is important
46
Can you have duplicate values in a list?
no
47
What is the first index place of a list?
0
48
Create a list in 2 different ways: 1) No values assigned 2) Values assigned
To create a list: • Use the new keyword • Use the List keyword followed by the element type contained within <> characters. Use the following syntax for creating a list: List list_name [= new List();] | [=new List{value [, value2. . .]};] | ;
49
Explain what a Set is and what types you contain in a Set.
A set is a collection of unique, unordered elements. It can contain primitive data types, such as String, Integer, Date, and so on. It can also contain more complex data types, such as sObjects.
50
Write a Set with the values a, b, c assigned to it
The following example creates a set of String. The values for the set are passed in using the curly braces {}. Set My_String = new Set{'a', 'b', 'c'};
51
Describe what a map is? | What kind of data types can be used in a map?
A map is a collection of key-value pairs. Keys can be any primitive data type. Values can include primitive data types, as well as objects and other collections.
52
When should you use a map?
Use a map when finding something by key matters.
53
Can you have multiple values in a map?
You can have duplicate values in a map, | but each key must be unique.
54
Write a map:
``` To create a map: • Use the new keyword • Use the Map keyword followed by a key-value pair, delimited by a comma and enclosed in <> characters. Use the following syntax for creating a map: Map map_name [=new map();] | [=new map {key1_value => value1_value [, key2_value => value2_value. . .]};] | ; ```
55
Write a map with keys 1,2,3 and values a,b,c in the order presented
The following example creates a map that has a data type of Integer for the key and String for the value. In this example, the values for the map are being passed in between the curly braces {} as the map is being created. Map My_Map = new Map{1 => 'a', 2 => 'b', 3 => 'c'};
56
How do you declare a map with a nested collection and how many levels deep can you nest?
Map keys and values can contain any collection, and can contain nested collections. For example, you can have a map of Integers to maps, which, in turn, map Strings to lists. Map keys can contain up to only four levels of nested collections. ``` To declare a map, use the Map keyword followed by the data types of the key and the value within <> characters. For example: Map country_currencies = new Map(); Map> m = new Map>(); ```
57
What is a generic sObject in Salesforce?
Similar to the SOAP API, Apex allows the use of the generic sObject abstract type to represent any object. The sObject data type can be used in code that processes different types of sObjects. The new operator still requires a concrete sObject type, so all instances are specific sObjects. For example: sObject s = new Account();
58
Write the line of code to add a string value "abc" to this map to key =1 : Map m = new Map();
m.put (1, 'abc');
59
Write the line of code that will return the set of keys from this map: ``` Map m = new Map(); // Define a new map m.put(1, 'First entry'); // Insert a new key-value pair in the map m.put(2, 'Second entry'); // Insert a new key-value pair in the map System.assert(m.containsKey(1)); // Assert that the map contains a key String value = m.get(2); // Retrieve a value, given a particular key System.assertEquals('Second entry', value); ```
Set s = m.keySet(); // Return a set that contains all of the keys in the map
60
When writing a map, in which instances should you have to reference a hashtable?
Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a map in their declarations (for example, HashMap or TreeMap). Apex uses a hash structure for all maps.
61
How do you order values returned by a map
You cannot Do not rely on the order in which map results are returned. The order of objects returned by maps may change without warning. Always access map elements by key.
62
Can a map key hold a null value?
Yes. A map key can hold the null value.
63
What happens when adding a map entry with a key that matches an existing key
Adding a map entry with a key that matches an existing key in the map overwrites the existing entry with that key with the new entry.
64
What is the result of 2 map keys being: a) 'Holiday' b) 'HOLIDAY'
Map keys of type String are case-sensitive. Two keys that differ only by the case are considered unique and have corresponding distinct Map entries. Subsequently, the Map methods, including put, get, containsKey, and remove treat these keys as distinct.
65
Statement: | Map key uniqueness
Uniqueness of map keys of user-defined types is determined by the equals and hashCode methods, which you provide in your classes. Uniqueness of keys of all other non-primitive types, such as sObject keys, is determined by comparing the objects’ field values.
66
What does Parameterized Typing mean?
Apex, in general, is a statically-typed programming language, which means users must specify the data type for a variable before that variable can be used. For example, the following is legal in Apex: Integer x = 1; The following is not legal if x has not been defined earlier: x = 1;
67
What should you avoid using object names for class names? EG Public class Account
Avoid using standard object names for class names. Doing so causes unexpected results
68
What syntax can you use when defining a class?
``` Use the following syntax for defining classes: private | public | global [virtual | abstract | with sharing | without sharing | (none)] class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)] { ```
69
Write an enum statement that publicly accessible with all the seasons assigned to it
An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums are typically used to define a set of possible values that don’t otherwise have a numerical order, such as the suit of a card, or a particular season of the year. Although each value corresponds to a distinct integer value, the enum hides this implementation so that you don’t inadvertently misuse the values, such as using them to perform arithmetic. After you create an enum, variables, method arguments, and return types can be declared of that type. Note: Unlike Java, the enum type itself has no constructor syntax. To define an enum, use the enum keyword in your declaration and use curly braces to demarcate the list of possible values. For example, the following code creates an enum called Season: public enum Season {WINTER, SPRING, SUMMER, AUTUMN}
70
Write a line of code that defines an enum as a public class with values x and y assigned
``` You can also define a class as an enum. Note that when you create an enum class you do not use the class keyword in the definition. public enum MyEnumClass { X, Y } ```
71
What happens if you assign an object to an enum variable?
You can use an enum in any place you can use another data type name. If you define a variable whose type is an enum, any object you assign to it must be an instance of that enum class.
72
What happens when a webService methods can use enum types as part of their signature?
Any webService methods can use enum types as part of their signature. When this occurs, the associated WSDL file includes definitions for the enum and its values, which can then be used by the API client.
73
What is a WSDL and what does it stand for?
The Web Services Description Language (WSDL pronounced "wiz'-dul") is an XML-based interface description language that is used for describing the functionality offered by a web service. The acronym is also used for any specific WSDL description of a web service (also referred to as a WSDL file), which provides a machine-readable description of how the service can be called, what parameters it expects, and what data structures it returns. It thus serves a purpose that corresponds roughly to that of a method signature in a programming language.
74
What is an argument?
In programming, a value that you pass to a routine. For example, if SQRT is a routine that returns the square root of a value, then SQRT(25) would return the value 5. The value 25 is the argument. Argument is often used synonymously with parameter, although parameter can also mean any value that can be changed. In addition, some programming languages make a distinction between arguments, which are passed in only one direction, and parameters, which can be passed back and forth, but this distinction is by no means universal.
75
Write a line of code that declares 3 numerical variable X Y Z
Integer x, y, z;
76
Write a line of code that can define a list called myList and add the elements 4 5 6 7
List myList = new List { 4,5,6,7};
77
In the code below does b = false or null?
Null A common pitfall is to assume that an uninitialized boolean variable is initialized to false by the system. This isn’t the case. Like all other variables, boolean variables are null if not assigned a value explicitly. Variable
78
Can a class be static?
Apex classes can’t be static. | https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_static.htm
79
Write the code that house an outer class that contains an inner class
``` In Apex, you can define top-level classes (also called outer classes) as well as inner classes, that is, a class defined within another class. You can only have inner classes one level deep. For example: public class myOuterClass { // Additional myOuterClass code here class myInnerClass { // myInnerClass code here } } ```
80
Can you use static methods and variables with inner classes?
You can only use static methods and variables with outer classes. https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_static.htm
81
When are static member variables, initialization code run in apex? And which order do they run?
All static member variables in a class are initialized before any object of the class is created. This includes any static initialization code blocks. All of these are run in the order in which they appear in the class.
82
What are static methods generally used for?
Static methods are generally used as utility methods and never depend on a particular instance member variable value. Because a static method is only associated with a class, it cannot access any instance member variable values of its class.
83
Are Static variable static across the server or across the entire organisation?
Static variables are only static within the scope of the request. They’re not static across the server, or across the entire organization.
84
When talking about variables, what is the variable scope?
``` Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks can’t redefine a variable name that has already been used in a parent block, but parallel blocks can reuse a variable name. For example: Integer i; { // Integer i; This declaration is not allowed } for (Integer j = 0; j < 10; j++); for (Integer j = 0; j < 10; j++); ```
85
Is Apex case sensitive in general?
No
86
Is s < b? String s; System.assert('a' == 'A'); System.assert(s < 'b'); System.assert(!(s > 'b'));
Note: Although s < 'b' evaluates to true in the example above, 'b.'compareTo(s) generates an error because you’re trying to compare a letter to a null value.
87
How do you define a constant in Apex?
``` Apex constants are variables whose values don’t change after being initialized once. Constants can be defined using the final keyword, which means that the variable can be assigned at most once, either in the declaration itself, or with a static initializer method if the constant is defined in a class. This example declares two constants. The first is initialized in the declaration statement. The second is assigned a value in a static block by calling a static method. public class myCls { static final Integer PRIVATE_INT_CONST = 200; static final Integer PRIVATE_INT_CONST2; public static Integer calculate() { return 2 + 7; } static { PRIVATE_INT_CONST2 = calculate(); } } ```
88
What is an expression in Apex?
An expression is a construct made up of variables, operators, and method invocations that evaluates to a single value. In Apex, an expression is always one of the following types: • A literal expression. For example: 1 + 1 • A new sObject, Apex object, list, set, or map. For example: new Account() new Integer[] new Account[]{} new List() new Set{} new Map() new myRenamingClass(string oldName, string newName) • Any value that can act as the left-hand of an assignment operator (L-values), including variables, one-dimensional list positions, and most sObject or Apex object field references. For example: Integer i myList[3] myContact. Any sObject field reference that is not an L-value, including: ◊ The ID of an sObject in a list (see Lists) ◊ A set of child records associated with an sObject (for example, the set of contacts associated with a particular account). This type of expression yields a query result, much like SOQL and SOSL queries. • A SOQL or SOSL query surrounded by square brackets, allowing for on-the-fly evaluation in Apex. For example: Account[] aa = [SELECT Id, Name FROM Account WHERE Name ='Acme']; Integer i = [SELECT COUNT() FROM Contact WHERE LastName ='Weissman']; List> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead]; A static or instance method invocation. For example: System.assert(true) myRenamingClass.replaceNames() changePoint(new Point(x, y));
89
Write the code for a one dimensional list for accounts. Then another line to add an account call "acme2" to the list
``` Account[] accts = new Account[1]; This example adds an element to the list using square brackets. accts[0] = new Account(Name='Acme2'); ```
90
When talking about list with which data types can you use the square brackets []
sObjects
91
What does this expression operator mean? '=' 'x = y'
``` Assignment operator (Right associative). Assigns the value of y to the L-value x. Note that the data type of x must match the data type of y, and cannot be null. ```
92
What does this expression operator mean? '+=' x += y
Addition assignment operator (Right associative). Adds the value of y to the original value of x and then reassigns the new value to x. See + for additional information. x and y cannot be null.
93
*= x *= y
Multiplication assignment operator (Right associative). Multiplies the value of y with the original value of x and then reassigns the new value to x. Note *= x *= y that x and y must be Integers or Doubles, or a combination. x and y cannot be null.
94
-= x -= y
Subtraction assignment operator (Right associative). Subtracts the value of y from the original value of x and then reassigns the new value to x. Note that x and y must be Integers or Doubles, or a combination. x and y cannot be null.
95
x /= y
Division assignment operator (Right associative). Divides the original value of x with the value of y and then reassigns the new value to x. Note that x and y must be Integers or Doubles, or a combination. x and y cannot be null.
96
|= x |= y
OR assignment operator (Right associative). If x, a Boolean, and y, a Boolean, are both false, then x remains false. Otherwise, x is assigned the value of true. Note: • This operator exhibits “short-circuiting” behavior, which means y is evaluated only if x is false. • x and y cannot be null.
97
&= | x &= y
AND assignment operator (Right associative). If x, a Boolean, and y, a Boolean, are both true, then x remains true. Otherwise, x is assigned the value of false. Note: • This operator exhibits “short-circuiting” behavior, which means y is evaluated only if x is true. • x and y cannot be null.
98
<<<= y
Bitwise shift left assignment operator. Shifts each bit in x to the left by y bits so that the high order bits are lost, and the new right bits are set to 0. This value is then reassigned to x.
99
>>= | x >>= y
Bitwise shift right signed assignment operator. Shifts each bit in x to the right by y bits so that the low order bits are lost, and the new left bits are set to 0 for positive values of y and 1 for negative values of y. This value is then reassigned to x.
100
>>>= | x >>>= y
Bitwise shift right unsigned assignment operator. Shifts each bit in x to the right by y bits so that the low order bits are lost, and the new left bits are set to 0 for all values of y. This value is then reassigned to x.
101
? : | x ? y : z
``` Ternary operator (Right associative). This operator acts as a short-hand for if-then-else statements. If x, a Boolean, is true, y is the result. Otherwise z is the result. Note that x cannot be null. ```
102
&& | x && y
AND logical operator (Left associative). If x, a Boolean, and y, a Boolean, are both true, then the expression evaluates to true. Otherwise the expression evaluates to false. Note: • && has precedence over || • This operator exhibits “short-circuiting” behavior, which means y is evaluated only if x is true. • x and y cannot be null.
103
|| | x || y
OR logical operator (Left associative). If x, a Boolean, and y, a Boolean, are both false, then the expression evaluates to false. Otherwise the expression evaluates to true. Note: • && has precedence over || • This operator exhibits “short-circuiting” behavior, which means y is evaluated only if x is false. • x and y cannot be null.
104
== | x == y
Equality operator. If the value of x equals the value of y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: == x == y • Unlike Java, == in Apex compares object value equality, not reference equality, except for user-defined types. Consequently: ◊ String comparison using == is case insensitive ◊ ID comparison using == is case sensitive, and does not distinguish between 15-character and 18-character formats ◊ User-defined types are compared by reference, which means that two objects are equal only if they reference the same location in memory. You can override this default comparison behavior by providing equals and hashCode methods in your class to compare object values instead. • For sObjects and sObject arrays, == performs a deep check of all sObject field values before returning its result. Likewise for collections and built-in Apex objects. • For records, every field must have the same value for == to evaluate to true. • x or y can be the literal null. • The comparison of any two values can never result in null. • SOQL and SOSL use = for their equality operator, and not ==. Although Apex and SOQL and SOSL are strongly linked, this unfortunate syntax discrepancy exists because most modern languages use = for assignment and == for equality. The designers of Apex deemed it more valuable to maintain this paradigm than to force developers to learn a new assignment operator. The result is that Apex developers must use == for equality tests in the main body of the Apex code, and = for equality in SOQL and SOSL queries.
105
=== | x === y
Exact equality operator. If x and y reference the exact same location in memory, the expression evaluates to true. Otherwise, the expression evaluates to false.
106
< | x < y
Less than operator. If x is less than y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • Unlike other database stored procedures, Apex does not support tri-state Boolean logic, and the comparison of any two values can never result in null. • If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false. • A non-null String or ID value is always greater than a null value. • If x and y are IDs, they must reference the same type of object. Otherwise, a runtime error results. • If x or y is an ID and the other value is a String, the String value is validated and treated as an ID. • x and y cannot be Booleans. • The comparison of two strings is performed according to the locale of the context user.
107
> | x > y
Greater than operator. If x is greater than y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • The comparison of any two values can never result in null. • If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false. • A non-null String or ID value is always greater than a null value. • If x and y are IDs, they must reference the same type of object. Otherwise, a runtime error results. • If x or y is an ID and the other value is a String, the String value is validated and treated as an ID. • x and y cannot be Booleans. • The comparison of two strings is performed according to the locale of the context user.
108
<= y
Less than or equal to operator. If x is less than or equal to y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • The comparison of any two values can never result in null. • If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false. • A non-null String or ID value is always greater than a null value. • If x and y are IDs, they must reference the same type of object. Otherwise, a runtime error results. • If x or y is an ID and the other value is a String, the String value is validated and treated as an ID. • x and y cannot be Booleans. • The comparison of two strings is performed according to the locale of the context user.
109
>= | x >= y
Greater than or equal to operator. If x is greater than or equal to y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • The comparison of any two values can never result in null. • If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false. • A non-null String or ID value is always greater than a null value. • If x and y are IDs, they must reference the same type of object. Otherwise, a runtime error results. • If x or y is an ID and the other value is a String, the String value is validated and treated as an ID. • x and y cannot be Booleans. • The comparison of two strings is performed according to the locale of the context user.
110
!= | x != y
Inequality operator. If the value of x does not equal the value of y, the expression evaluates to true. Otherwise, the expression evaluates to false. Note: • Unlike Java, != in Apex compares object value equality, not reference equality, except for user-defined types. • For sObjects and sObject arrays, != performs a deep check of all sObject field values before returning its result. • For records, != evaluates to true if the records have different values for any field. • User-defined types are compared by reference, which means that two objects are different only if they reference different locations in memory. You can override this default comparison behavior by providing equals and hashCode methods in your class to compare object values instead. • x or y can be the literal null. • The comparison of any two values can never result in null.
111
!== | x !== y
Exact inequality operator. If x and y do not reference the exact same location in memory, the expression evaluates to true. Otherwise, the expression evaluates to false.
112
+ | x + y
Addition operator. Adds the value of x to the value of y according to the following rules: • If x and y are Integers or Doubles, adds the value of x to the value of y. If a Double is used, the result is a Double. • If x is a Date and y is an Integer, returns a new Date that is incremented by the specified number of days. • If x is a Datetime and y is an Integer or Double, returns a new Date that is incremented by the specified number of days, with the fractional portion corresponding to a portion of a day. • If x is a String and y is a String or any other type of non-null argument, concatenates y to the end of x.
113
- | x - y
Subtraction operator. Subtracts the value of y from the value of x according to the following rules: • If x and y are Integers or Doubles, subtracts the value of x from the value of y. If a Double is used, the result is a Double. • If x is a Date and y is an Integer, returns a new Date that is decremented by the specified number of days. • If x is a Datetime and y is an Integer or Double, returns a new Date that is decremented by the specified number of days, with the fractional portion corresponding to a portion of a day.
114
* | x * y
Multiplication operator. Multiplies x, an Integer or Double, with y, another Integer or Double. Note that if a double is used, the result is a Double
115
/ | x / y
Division operator. Divides x, an Integer or Double, by y, another Integer or Double. Note that if a double is used, the result is a Double.
116
! | !x
Logical complement operator. Inverts the value of a Boolean, so that true becomes false, and false becomes true.
117
- | -x
Unary negation operator. Multiplies the value of x, an Integer or Double, by -1. Note that the positive equivalent + is also syntactically valid, but does not have a mathematical effect.
118
++ x++ ++x
``` Increment operator. Adds 1 to the value of x, a variable of a numeric type. If prefixed (++x), the expression evaluates to the value of x after the increment. ``` ``` If postfixed (x++), the expression evaluates to the value of x before the increment. ```
119
-- x-- --x
Decrement operator. Subtracts 1 from the value of x, a variable of a numeric type. If prefixed (--x), the expression evaluates to the value of x after the decrement. If postfixed (x--), the expression evaluates to the value of x before the decrement.
120
What does bitwise mean?
In digital computer programming, a bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations. On simple low-cost processors, typically, bitwise operations are substantially faster than division, several times faster than multiplication, and sometimes significantly faster than addition. While modern processors usually perform addition and multiplication just as fast as bitwise operations due to their longer instruction pipelines and other architectural design choices, bitwise operations do commonly use less power because of the reduced use of resources.
121
& | x & y
Bitwise AND operator. ANDs each bit in x with the corresponding bit in y so that the result bit is set to 1 if both of the bits are set to 1. This operator is not valid for types Long or Integer.
122
| | x | y
Bitwise OR operator. ORs each bit in x with the corresponding bit in y so that the result bit is set to 1 if at least one of the bits is set to 1. This operator is not valid for types Long or Integer.
123
^ | x ^ y
Bitwise exclusive OR operator. Exclusive ORs each bit in x with the corresponding bit in y so that the result bit is set to 1 if exactly one of the bits is set to 1 and the other bit is set to 0.
124
^= | x ^= y
Bitwise exclusive OR operator. Exclusive ORs each bit in x with the corresponding bit in y so that the result bit is set to 1 if exactly one of the bits is set to 1 and the other bit is set to 0.
125
<< | x << y
Bitwise shift left operator. Shifts each bit in x to the left by y bits so that the high order bits are lost, and the new right bits are set to 0.
126
>> | x >> y
Bitwise shift right signed operator. Shifts each bit in x to the right by y bits so that the low order bits are lost, and the new left bits are set to 0 for positive values of y and 1 for negative values of y.
127
>>> | x >>> y
Bitwise shift right unsigned operator. Shifts each bit in x to the right by y bits so that the low order bits are lost, and the new left bits are set to 0 for all values of y.
128
() | x
Parentheses. Elevates the precedence of an expression x so that it is evaluated first in a compound expression.
129
What are the commands used for: 1) single line commenting 2) multi line commenting
``` // /* */ ```
130
What does Lvalue stand for?
Left value in any assignment statement
131
Write the line of code for a SOQL query that feeds directly into a one dimensional Account list called accts
Account[] accts = [SELECT Id FROM Account];
132
What is an assignment statement?
An assignment statement is any statement that places a value into a variable, generally in one of the following two forms: [LValue] = [new_value_expression]; [LValue] = [[inline_soql_query]];
133
What is wrong with this code? a.CreatedDate = System.today();
Cannot write to the created date unless turned on by SF support
134
Write a map statement that has a key of number and value of custom object invoice statement. Then add key=1, value=a to the map
Map map1 = new Map {}; | map1.put(1, a);
135
Why will this code throw a runtime exception? ``` insert new Account(Name = 'Singha'); Account acc = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1]; // Note that name is not selected String name = [SELECT Id FROM Account WHERE Name = 'Singha' LIMIT 1].Name; ```
In the second SOQL it does not include Name in the Select statement
136
What is the meaning of dereference
obtain the address of a data item held in another location from (a pointer). EG a de-referenced list element ``` ints[0] = 1; accts[0].Name = 'Acme'; ```
137
Can two lists can point at the same value in memory? ``` Account[] a = new Account[]{new Account()}; Account[] b = a; a[0].Name = 'Acme'; System.assert(b[0].Name == 'Acme'); ```
Yes
138
What is the meaning of explicit?
explicit adjective 1. stated clearly and in detail, leaving no room for confusion or doubt.
139
What is the meaning of implicit?
implicit adjective 1. suggested though not directly expressed.
140
Can you implicitly convert a data type of integer to string?
No, a variable of the Integer data type cannot be implicitly converted to a String. You must use the string.format method. However, a few data types can be implicitly converted, without using a method. Numbers form a hierarchy of types. Variables of lower numeric types can always be assigned to higher types without explicit conversion. The following is the hierarchy for numbers, from lowest to highest: 1. Integer 2. Long 3. Double 4. Decimal Note: Once a value has been passed from a number of a lower type to a number of a higher type, the value is converted to the higher type of number.
141
More info regarding conversions of data types
In addition to numbers, other data types can be implicitly converted. The following rules apply: • IDs can always be assigned to Strings. • Strings can be assigned to IDs. However, at runtime, the value is checked to ensure that it is a legitimate ID. If it is not, a runtime exception is thrown. • The instanceOf keyword can always be used to test whether a string is an ID.
142
Conversion info | Data Types of Numeric Values
Numeric values represent Integer values unless they are appended with L for a Long or with .0 for a Double or Decimal. For example, the expression Long d = 123; declares a Long variable named d and assigns it to an Integer numeric 47 Data Types and Variables Understanding Rules of Conversion value (123), which is implicitly converted to a Long. The Integer value on the right hand side is within the range for Integers and the assignment succeeds. However, if the numeric value on the right hand side exceeds the maximum value for an Integer, you get a compilation error. In this case, the solution is to append L to the numeric value so that it represents a Long value which has a wider range, as shown in this example: Long d = 2147483648L;.
143
Conversion info | Overflow of Data Type Values
Arithmetic computations that produce values larger than the maximum value of the current type are said to overflow. For example, Integer i = 2147483647 + 1; yields a value of –2147483648 because 2147483647 is the maximum value for an Integer, so adding one to it wraps the value around to the minimum negative value for Integers, –2147483648. If arithmetic computations generate results larger than the maximum value for the current type, the end result will be incorrect because the computed values that are larger than the maximum will overflow. For example, the expression Long MillsPerYear = 365 * 24 * 60 * 60 * 1000; results in an incorrect result because the products of Integers on the right hand side are larger than the maximum Integer value and they overflow. As a result, the final product isn't the expected one. You can avoid this by ensuring that the type of numeric values or variables you are using in arithmetic operations are large enough to hold the results. In this example, append L to numeric values to make them Long so the intermediate products will be Long as well and no overflow occurs. The following example shows how to correctly compute the amount of milliseconds in a year by multiplying Long numeric values. Long MillsPerYear = 365L * 24L * 60L * 60L * 1000L; Long ExpectedValue = 31536000000L; System.assertEquals(MillsPerYear, ExpectedValue);
144
Conversion info | Loss of Fractions in Divisions
When dividing numeric Integer or Long values, the fractional portion of the result, if any, is removed before performing any implicit conversions to a Double or Decimal. For example, Double d = 5/3; returns 1.0 because the actual result (1.666...) is an Integer and is rounded to 1 before being implicitly converted to a Double. To preserve the fractional value, ensure that you are using Double or Decimal numeric values in the division. For example, Double d = 5.0/3.0; returns 1.6666666666666667 because 5.0 and 3.0 represent Double values, which results in the quotient being a Double as well and no fractional value is lost.
145
What are Control Flow Statements?
* Conditional (If-Else) Statements * Loops Apex provides statements that control the flow of code execution. Statements are generally executed line by line, in the order they appear. With control flow statements, you can cause Apex code to execute based on a certain condition or you can have a block of code execute repeatedly. This section describes these control flow statements: if-else statements and loops.
146
``` Write an else if statement that looks at place variable and if: == 1 medal color = gold == 2 medal color = silver == 3 medal color = bronze Otherwise null ```
``` if (place == 1) { medal_color = 'gold'; } else if (place == 2) { medal_color = 'silver'; } else if (place == 3) { medal_color = 'bronze'; } else { medal_color = null; } ```
147
What are the 5 types of loops?
* do {statement} while (Boolean_condition); * while (Boolean_condition) statement; * for (initialization; Boolean_exit_condition; increment) statement; * for (variable : array_or_set) statement; * for (variable : [inline_soql_query]) statement;
148
Which loop control structures do all 5 types of loops allow?
* break; exits the entire loop | * continue; skips to the next iteration of the loop
149
Explain what a do while loop does?
The Apex do-while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax is: do { code_block } while (condition); Note: Curly braces ({}) are always required around a code_block. boolean at end of statement
150
Write a do while code block that outputs the numbers 1 - 10 into the debug log
``` Integer count = 1; do { System.debug(count); count++; } while (count < 11); ```
151
What does a while loop do?
The Apex while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax is: while (condition) { code_block } Note: Curly braces ({}) are required around a code_block only if the block contains more than one statement. Unlike do-while, the while loop checks the Boolean condition statement before the first loop is executed. Consequently, it is possible for the code block to never execute. ``` As an example, the following code outputs the numbers 1 - 10 into the debug log: Integer count = 1; while (count < 11) { System.debug(count); count++; } ```
152
What are the 4 types of four loops?
``` The traditional for loop: for (init_stmt; exit_condition; increment_stmt) { code_block } • The list or set iteration for loop: for (variable : list_or_set) { code_block } where variable must be of the same primitive or sObject type as list_or_set. • The SOQL for loop: for (variable : [soql_query]) { code_block } or for (variable_list : [soql_query]) { code_block } ```
153
How is a traditional for loop structured?
for (init_stmt; exit_condition; increment_stmt) { code_block } When executing this type of for loop, the Apex runtime engine performs the following steps, in order: 1. Execute the init_stmt component of the loop. Note that multiple variables can be declared and/or initialized in this statement. 2. Perform the exit_condition check. If true, the loop continues. If false, the loop exits. 3. Execute the code_block. 4. Execute the increment_stmt statement. 5. Return to Step 2.
154
Write a traditional for loop that outputs the numbers 1 - 10 into the debug log incrementally
Note that an additional initialization variable, j, is included to demonstrate the syntax: for (Integer i = 0, j = 0; i < 10; i++) { System.debug(i+1); }
155
What is the code structure for a list or set iteration for loop
The list or set iteration for loop iterates over all the elements in a list or set. Its syntax is: for (variable : list_or_set) { code_block }
156
When using a list or set iteration for loop can you use different data types for the variable and list or set?
No where variable must be of the same primitive or sObject type as list_or_set.
157
What's the difference in outputs between: a) Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; System.debug(i); b) Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (Integer i : myInts) { System.debug(i); }
a) Debug(1,2,3,4,5,6,7,8,9,10) ``` b) Debug 1 Debug 2 Debug 3 Debug 4 Debug 5 Debug 6 Debug 7 Debug 8 Debug 9 Debug 10 ```
158
How many soql queries can you have in runtest time?
100 | Not the same in production
159
How many soql queries can you have in production run time?
20
160
Iterating Collections
Collections can consist of lists, sets, or maps. Modifying a collection's elements while iterating through that collection is not supported and causes an error. Do not directly add or remove elements while iterating through the collection that includes them.
161
Write the code to firstly establish a list of integers values 1-10. The a for list that will output the numbers 1-10
Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (Integer i : myInts) { System.debug(i); }
162
How can you add list, set or map items during iteration?
Adding Elements During Iteration To add elements while iterating a list, set or map, keep the new elements in a temporary list, set, or map and add them to the original after you finish iterating the collection.
163
How can you remove list, set or map items during iteration?
Removing Elements During Iteration To remove elements while iterating a list, create a new list, then copy the elements you wish to keep. Alternatively, add the elements you wish to remove to a temporary list and remove them after you finish iterating the collection. Note: The List.remove method performs linearly. Using it to remove elements has time and resource implications. To remove elements while iterating a map or set, keep the keys you wish to remove in a temporary list, then remove them after you finish iterating the collection.
164
Describe a class and object setup using the purchase order analogy
``` An object is an instance of a class. For example, the PurchaseOrder class describes an entire purchase order, and everything that you can do with a purchase order. An instance of the PurchaseOrder class is a specific purchase order that you send or receive. ```
165
In a class what is used to specify the state of an object?
Variables EG. Object's Name or Type Descriptor
166
In a class what is used to control behaviour?
Methods The behavior of a PurchaseOrder object—what it can do—includes checking inventory, shipping a product, or notifying a customer. A class can contain variables and methods
167
What is an interface and why is it like a class?
``` An interface is like a class in which none of the methods have been implemented—the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface. ```
168
How many levels deep can you have an inner class from an outer class?
1
169
When is the only time you can put a soql statement in a for loop?
Never | Error msg 101 soql statements
170
What will happen when you add a dml inside of a for loop?
Error | 150 dmls
171
What are the 3 types of assertions for tests?
Assert Assert.equals Assert.notequals
172
In what instance should you have more than one trigger per object?
``` You shouldn't. And put the methods in a class and just call the methods and order execution in the trigger. ```