function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
bonny mankotiabonny mankotia 

Show Anonymous Error

Hello Guys.I have the following code its show an error Line: 16, Column: 1System.NullPointerException: Attempt to de-reference a null object.I want to know the reason behind this error.Is this not proper way to declare and initiliaze object like this way please help me.

public with sharing class MapExampleTwo 
{
    public void display()
    {
        account acc4;
        acc4.name = 'Peter';
        account acc5;
        acc5.name = 'corey';
        account acc = new account();
       acc.name = 'bonny';
       account acc1 = new account();
       acc1.name = 'bonsy';
       account acc3 = new account(name = 'bonson');
       map<integer,account>map1 = new map<integer,account>{0 => acc,1 => acc1,2 => acc3};
       system.debug('The first index is' + map1.get(0));
       system.debug('====='+map1.keyset());
       system.debug('===='+map1.values());
   }
}
Amit Chaudhary 8Amit Chaudhary 8
You are trying to access acc4.Name and acc5.name without creating the object. So please create object first before using the field
PLease try below code.
public with sharing class MapExampleTwo 
{
    public void display()
    {
        account acc4 = new Account();
        acc4.name = 'Peter';

        account acc5= new Account();
        acc5.name = 'corey';
        
		account acc = new account();
        acc.name = 'bonny';
        
		account acc1 = new account();
        acc1.name = 'bonsy';

        account acc3 = new account(name = 'bonson');
		map<integer,account>map1 = new map<integer,account>{0 => acc,1 => acc1,2 => acc3};
        system.debug('The first index is' + map1.get(0));
        system.debug('====='+map1.keyset());
        system.debug('===='+map1.values());
   }
}

 
Waqar Hussain SFWaqar Hussain SF
public with sharing class MapExampleTwo 
{
    public void display()
    {
        Account acc4 = new Account();;
        acc4.name = 'Peter';
        insert acc4;

        account acc5 = new account();
        acc5.name = 'corey';
        insert acc5;

        account acc = new account();
       acc.name = 'bonny';
       insert acc;

       account acc1 = new account();
       acc1.name = 'bonsy';
       insert acc1;

       account acc3 = new account(name = 'bonson');
       insert acc3;

       map<integer,account>map1 = new map<integer,account>{0 => acc,1 => acc1,2 => acc3};
       system.debug('The first index is' + map1.get(0));
       system.debug('====='+map1.keyset());
       system.debug('===='+map1.values());
   }
}