How to resolve Dependency ‘androidx.appcompat:appcompat:1.4.1’ requires ‘compileSdkVersion’ to be set to 31 or higher.Compilation target for module ‘:app’ is ‘android-30’

I had the below problem when building code for an older version of Android on Android Studio.

Dependency 'androidx.appcompat:appcompat:1.4.1' requires 'compileSdkVersion' to be set to 31 or higher.Compilation target for module ':app' is 'android-30'

I was able to solve it by changing the version of appcompat in the dependencies What I had:

implementation 'androidx.appcompat:appcompat:1.4.0'

I changed it to:

implementation 'androidx.appcompat:appcompat:1.3.1'

Note that I am using java.