You need to sign in to do that
Don't have an account?
Vishnu N
Hi I'm Getting an error while trying to Execute an array in Anonymous Window
Apex class:
public class Arrays_Example {
public void Example1(){
Account[] accounts = new Account[4];
Account a1 = new Account();
a1.Name = 'TCS';
a1.Phone = '1111';
a1.Rating = 'Hot';
accounts[0]=a1;
Account a2 = new Account();
a2.Name = 'Dell';
a2.Phone = '2222';
a2.Rating = 'Warm';
accounts[1]=a2;
Account a3 = new Account();
a3.Name='CapG';
a3.Phone='3333';
a3.Rating='Cold';
accounts[3]=a3;
for (Integer i = 0; i<accounts.size();i++){
System.debug('Name: '+ accounts[i].Name);
System.debug('Phone: '+accounts[i].Phone);
System.debug('Rating: '+ accounts[i].Rating);
}
}
}
And Trying to executute with the statement.
Arrays_Example acc = new Arrays_Example();
acc.Example1();
But getting error :
System.NullPointerException: Attempt to de-reference a null object.
There is no error in class while executing getting error. Can someone run the code and help me with the answer. Thanks
public class Arrays_Example {
public void Example1(){
Account[] accounts = new Account[4];
Account a1 = new Account();
a1.Name = 'TCS';
a1.Phone = '1111';
a1.Rating = 'Hot';
accounts[0]=a1;
Account a2 = new Account();
a2.Name = 'Dell';
a2.Phone = '2222';
a2.Rating = 'Warm';
accounts[1]=a2;
Account a3 = new Account();
a3.Name='CapG';
a3.Phone='3333';
a3.Rating='Cold';
accounts[3]=a3;
for (Integer i = 0; i<accounts.size();i++){
System.debug('Name: '+ accounts[i].Name);
System.debug('Phone: '+accounts[i].Phone);
System.debug('Rating: '+ accounts[i].Rating);
}
}
}
And Trying to executute with the statement.
Arrays_Example acc = new Arrays_Example();
acc.Example1();
But getting error :
System.NullPointerException: Attempt to de-reference a null object.
There is no error in class while executing getting error. Can someone run the code and help me with the answer. Thanks
Few corrections suggested for this code are highlighted in bold. These changes will help fix the error
The for loop iterates in sequence. As there was no accounts[2] after accounts[0],accounts[1] it would throw null exception.
Also, when you add system.debug(accounts.size()) it would give 4. System.debug( accounts[i]) will have a null value in this scenario. When trying accounts[i].Name , Null. Name will result in null exception again.
If this information helps, please mark the answer as best. Thank you
When you execute your code then you will see, one null value there. that's why error happened
Reason : you skip one Index of array that's why this error
if you need any assistanse, Please let me know!!
Kindly mark my solution as the best answer if it helps you.
Thanks
Mukesh