Here is the code that you should add to your .htaccess file (you will find it in root folder of Joomla)

non-www to www redirect

RewriteEngine On
RewriteCond %{HTTP_HOST} ^yoursitename.com [NC]
RewriteRule ^(.*)$ http://www.yoursitename.com/$1 [L,R=301]

www to non-www redirect:

RewriteEngine On
RewriteCond %{HTTP_HOST} www.yoursitename.com
RewriteRule (.*) http://yoursitename.com/$1 [R=301,L]