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

diff bet List<Account> a=[Select id,name from account] &List<Account> a=new List<Account>([ Select id,name from account]);

Hi ,
Whats's the difference between:
List<Account> a=[Select id,name from account];
List<Account> a=new List<Account>([ Select id,name from account]);
Thanks in advance.
PratikPratik (Salesforce Developers) 
Hi Ramlakhan,

These are 2 different methods of defining list collection variable. 
You can define List in the initial part of code (List<Account> a=new List<Account>) and use it afterwords or you can define it and there itself you can add the records in it.  The above mentioned syntax is same if you are adding the list of recod immediately after definition of List, but if you want to use it in other part of code, you can define it before and then use it. ( 2nd part of your code).

List<Account> a=new List<Account>();
a= ([ Select id,name from account]);

sandeep sankhlasandeep sankhla
Hi Ramlakhan,

List<Account> a=[Select id,name from account];

if your query returns no records then in this case if you will use this list any where or use the size also to check if size is greater than zero it will throw an error...a will be null and you will not be able to use anywhere..

However , for second code it will not throw any error if you check the size when it returns zero records...

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Salesforce Certified Developer