Reputation: 4239
This is my first time trying to use external java libraries. For clarity, I am using a Mac laptop. And I am coding in Emacs.
Here is what I did:
commons-math3-3.3
into Library/Java/Extension
. import import org.apache.commons.math3;
in
the Hello.java
But I got the following error:
error: package org.apache.commons does not exist
import org.apache.commons.math3;
^
1 error
What is the correct way to store external Java libraries into my Mac ? And I am confused why am I import a library with name that is inconsistent with the name of the folder that I just downloaded. What is the correct way to approach this ?
Upvotes: 1
Views: 797
Reputation: 12883
If you're using straight up javac, you would tell it about the jar file with the classpath flag.
e.g.
javac -cp your_jar_file.jar YourClass.java
Then you'd need to make sure it was added to the classpath when you attempt to run your file too.
java -cp your_jar_file.jar:some_directory_with_class_files YourClass
As mentioned by GreyBeardedGeek above the CLASSPATH variable is one way to do this, although the -cp flag on the command line works too.
This can get cumbersome very quickly, and it's why IDEs became popular. They manage this sort of thing for you. Although not always very well, so this is why build tools like Ant and Gradle exist and are still popular.
If you're just learning Java, using an IDE is nice because you can focus on learning Java and not futzing with the classpath.
Upvotes: 2
Reputation: 30088
Library/Java/Extension is not the proper place for this.
Java library dependencies can be put anywhere, but in the typical java development scenario, the ".jar" files (and only the .jar files) are put in a sub-directory of the project, named "lib".
Then, at both compile-time and at run-time, those .jar files must be added to Java's classpath, either with a command-line argument or by setting CLASSPATH environment variable.
For non-trivial development scenarios, most developers use build tools / dependency managers. The current in-vogue tool is Gradle, though there's still lots of Maven and Ant in use.
See https://docs.oracle.com/javase/tutorial/deployment/jar/downman.html http://www.gradle.org/ and http://maven.apache.org/
Upvotes: 1