java.sql.SQLException: Access denied for user 'root'@'localhost' code example

Example 1: Got error: 1698: Access denied for user 'root'@'localhost' when trying to connect

$ sudo mysql -u root # I had to use "sudo" since is new installation

mysql> USE mysql;
mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> exit;

$ service mysql restart

Example 2: access denied for user 'root'@'localhost' mariadb

UPDATE mysql.user SET plugin = 'mysql_native_password' WHERE user = 'root' AND plugin = 'unix_socket';
FLUSH PRIVILEGES;