Java giving NoClassDefFoundError when importing maven package

I have a simple java code, I am trying to import the apache commons Fraction class from the apache commons math3 library. So, as a sample code, I put this in my

package myApp;
import org.apache.commons.math3.fraction.Fraction;

public class App 
    public static void main( String[] args )
        Fraction f = new Fraction(2, 3);
        System.out.println( "Hello World!" );
        System.out.println( f );

Using the following POM:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="" xmlns:xsi=""




    <!-- -->


    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
        <!-- clean lifecycle, see -->
        <!-- default lifecycle, jar packaging: see -->
        <!-- site lifecycle, see -->
            <!-- put your configurations here -->

I have tried to put the plugin suggested by utdemir in his answer to a similar question, but in my case, when I run:

mvn package
java -cp target/Proj1-1.0-SNAPSHOT.jar myApp.App

While it apparently compiles properly, I get the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/math3/fraction/Fraction
        at myApp.App.main(
Caused by: java.lang.ClassNotFoundException: org.apache.commons.math3.fraction.Fraction
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(
        at java.base/java.lang.ClassLoader.loadClass(
        ... 1 more

What should I do?

>Solution :

Its much easier to run your app using mvn, rathen than by calling java directly. This is because in the later case you need to manually set the classpath to the correct value using the -cp flag. This can lead to errors, like in your case.

Here’s how you can run your app using mvn

mvn exec:java -Dexec.mainClass="myApp.App"

More details can be found here

Leave a Reply