Error: Could not set unknown property 'sourceCompatibility' for root project

I am encountering the below error when upgrading from gradle 8.13 to gradle 9.4.

A problem occurred evaluating root project 'Project-Name'.
> Could not set unknown property 'sourceCompatibility' for root project 'Project-Name' of type org.gradle.api.Project.

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights from a Build Scan (powered by Develocity).
> Get more help at https://help.gradle.org.
Deprecated Gradle features were used in this build, making it incompatible with Gradle 10.
You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.
For more on this, please refer to  https://docs.gradle.org/9.4.0/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation.

Here is my code

allprojects {
    sourceCompatibility = javaVersion
    targetCompatibility = javaVersion
    tasks.withType(JavaCompile) {
        options.encoding = 'UTF-8'
        options.fork = true
        options.forkOptions.memoryMaximumSize = "2g"
    }
}

There is no issue with the 8.13 version. Could someone help me with the solution. Thanks

Before doing a major version upgrade, you should always update to the latest patch in the current major version and fix all deprecation warnings by Gradle, or you most likely get a broken build after upgrading.

If you run your build with 8.x again, you will see that you have a deprecation warning because you are using the java plugin convention to set the source compatibility which is deprecated since Gradle 8.2 and was removed in Gradle 9. Set it on the Java extension instead, so within java { ... }.

Thanks for the reply @Vampire