David showed repentance - a turning away from former actions and turning to God. And God's mercy allowed him to see himself as clean in the sight of God. This is a good lesson - God's not expecting us to harbor guilt for offenses we've repented of and He's "put away".
Here are David's words in a song from 2 Sameul 22, believed to be written after his terrible offenses. This is not just a mind trick - if I tell myself I'm clean, then I'm clean - this is David knowing God has cleaned him. See how He sees himself:
21 “The Lord dealt with me according to my righteousness;
according to the cleanness of my hands he rewarded me.
22 For I have kept the ways of the Lord
and have not wickedly departed from my God.
23 For all his rules were before me,
and from his statutes I did not turn aside.
24 I was blameless before him,
and I kept myself from guilt.
25 And the Lord has rewarded me according to my righteousness,
according to my cleanness in his sight.