www.example.com and example.com are considered as two different sites by Google and other search engines. The main domain is example.com and any other names like www.example.com are considered as a separate subdomains. Hence, you need to be careful and setup proper redirection between www and non- www versions of your site. Otherwise search engines will think the content is duplicated on two different sites and punish your domain for webspam.
Here is a free tool to generate a redirection directive between www and non-www versions of your site. Let us take an example that you have site with www.example.com. Now the first thing is you need to setup a preferred domain in Google Search Console account as www.example.com. Next, use our free tool to generate htaccess redirective from non-www to www version. Paste this code in your .htaccess file so that both the versions of your site will be redirected to the www.example.com version.
There are four steps in using this tool:
Check in browser that both www and non-www versions of your site are pointing to the correct site. Ensure to submit XML Sitemap for the correct version of your site in Google Search Console.