I need to import a Java class in my project. The class I need to import is in a JAR file with
absolute path ~/Documents/mylib/stdlib.jar
Now in my source file (Test.java) I am using
import stdlib.*;
and I am compiling with
javac -classpath ~/Documents/mylib/stdlib.jar Test.java
And it is showing the error that stdlib does not exist.
Is my import statement correct or is there anything wrong with classpath?
Shouldn't this import statement import all the classes present in the JAR file?
I am not using any IDE and my OS is Linux.
The import statement imports classes from the jar file, not the jar file itself.
An import statement of the form:
import stdlib.*;
will import all the classes in the package stdlib.
Oracle provides this tutorial on import.
EDIT: It looks like you're using the stdlib.jar for An introduction to programming in Java. The classes in this jar file have no packages. You don't need to import classes in the default package, since your class is also in the default package.
Use $HOME
instead of ~
.
$HOME is expanded, ~ is not.
It will import all classes immediately under the "stdlib" package, but nothing in sub-packages. You need to import the package(s) and classes; we can see inside the jar to know if your package name assumption is correct.
The class path itself is fine.
Updated with information from comments.
You say that you're trying to import a class in the default package. It is a syntax error to import a type from the default package. See the JLS Section 7.5 for details.
It is a compile time error to import a type from the unnamed package.
If you must access this class you'll need to use reflection.
It would be much easier to put it in a named package, though.
Check whether StdOut.java
has a declaration package stdout;
.
Or is it just situated on the top-level folder in stdout.jar
?